Defining bunch of vars dynamically

Discussion in 'Ruby' started by Eilie, Feb 7, 2012.

  1. Eilie

    Eilie Guest

    Hello, everyone.

    Subj on 1.9.3.
    I tryed already:

    5.times {|n| eval "house#{n} = Array.new(5)"}

    Thats works but only in block scope, how can i define 5 vars in global
    scope(with ability to access it out of block)?
     
    Eilie, Feb 7, 2012
    #1
    1. Advertisements

  2. Eilie

    sreservoir Guest

    you ... probably don't want to. having to dynamically generate your
    variable names is generally a sign that either you're using foreign data
    for them, or they're closely related. or both.

    in the former case, doing that would be unsafe, and you should probably
    use some sort of array (or a hash). the latter case ... you should also
    probably do that.
     
    sreservoir, Feb 7, 2012
    #2
    1. Advertisements

  3. Eilie

    Eilie Guest

    Yeah, you're right. Hash better choice for that, sorry for disturbance.
     
    Eilie, Feb 8, 2012
    #3
  4. Why not an Array? You are indexing by integer anyway.

    Assuming you really want five Arrays of length five each:

    houses = Array.new(5) { Array.new(5) }

    Cheers

    robert
     
    Robert Klemme, Feb 8, 2012
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.