Defining bunch of vars dynamically

E

Eilie

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)?
 
S

sreservoir

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)?

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.
 
E

Eilie

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.

Yeah, you're right. Hash better choice for that, sorry for disturbance.
 
R

Robert Klemme

Yeah, you're right. Hash better choice for that, sorry for disturbance.

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
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top