From: dblack@... Date: 2006-07-21T04:19:33+09:00 Subject: Re: Using .each with constructors Hi -- On Fri, 21 Jul 2006, 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" } That won't work. The variables will be local to the eval, and not available outside it. David -- http://www.rubypowerandlight.com => Ruby/Rails training & consultancy http://www.manning.com/black => RUBY FOR RAILS (reviewed on Slashdot, 7/12/2006!) http://dablog.rubypal.com => D[avid ]A[. ]B[lack's][ Web]log dblack@wobblini.net => me