From: Adam Shelly Date: 2007-12-13T07:41:34+09:00 Subject: Re: Creating multiple objects in loops On 12/11/07, Suraj Kurapati wrote: > Yes, the problem you pose is very well solvable (see below), but ... > > A wise Rubyist once said "eval is evil", so beware! > > >> array = %w[a b c] > => ["a", "b", "c"] > >> array.map {|x| "#{x} = Object.new" } > => ["a = Object.new", "b = Object.new", "c = Object.new"] > >> array.map {|x| "#{x} = Object.new" }.join('; ') > => "a = Object.new; b = Object.new; c = Object.new" > >> eval array.map {|x| "#{x} = Object.new" }.join('; ') > => # > >> a > => # > >> b > => # > >> c > => # > -- unfortunately, this only works in IRB, not in a script: C:\code>type dynamicVarNames.rb array = %w[a b c] p array.map {|x| "#{x} = Object.new" }.join('; ') eval array.map {|x| "#{x} = Object.new" }.join('; ') p a,b,c C:\code>ruby dynamicVarNames.rb "a = Object.new; b = Object.new; c = Object.new" dynamicVarNames.rb:5: undefined local variable or method `a' for main:Object (NameError) I'm not sure why, exactly. something about variable scope. Maybe some guru can explain. It will work if you set array = %w{@a @b @c}, but then you are creating instance variables, not locals= ones. -Adam