From: Mike Harris Date: 2006-07-21T06:47:39+09:00 Subject: Re: Using .each with constructors Mike Harris wrote: > Ben Zealley wrote: > >> Is there a nice elegant way of creating several named objects of the >> same class? I naively tried >> >> a,b,c,d = 0 >> [a, b, c, d].each { |o| o = SomeClass.new } >> >> and found that while they get initialised inside the block, they get >> destroyed leaving it. I can't believe >> >> a = SomeClass.new >> b = SomeClass.new >> etc. >> >> is the best way to do it. I can populate an array, but let's >> hypothesise that for reasons relating to irritating corporate coding >> standards, the variables need specific names... ;) >> >> Thoughts appreciated! Cheers >> >> >> > The parallel assignment/array expansion approach suggested by patrick > and james will definitely work. You could also try > > [:a,:b,:c,:d].each { |x| eval "#{x} = SomeClass.new" } > > You're right, it works if you do the a=b=c=d=0 line first to init scope outside the block. I tested with that and then forgot to include it.