Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Defining bunch of vars dynamically

13 views
Skip to first unread message

Eilie

unread,
Feb 7, 2012, 5:59:57 PM2/7/12
to
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)?

sreservoir

unread,
Feb 7, 2012, 6:08:08 PM2/7/12
to
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.

Eilie

unread,
Feb 7, 2012, 9:41:45 PM2/7/12
to
Yeah, you're right. Hash better choice for that, sorry for disturbance.

Robert Klemme

unread,
Feb 8, 2012, 9:44:06 AM2/8/12
to
On Wednesday, February 8, 2012 3:41:45 AM UTC+1, Eilie wrote:
> On 2012-02-07, sreservoir <srese...@gmail.com> wrote:
> > On 02/07/2012 05:59 PM, Eilie wrote:
> >> I tryed already:
> >>
> >> 5.times {|n| eval "house#{n} = Array.new(5)"}

> 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
0 new messages