Adam Shelly
12/12/2007 10:42:00 PM
On 12/11/07, Suraj Kurapati <snk@gna.org> 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('; ')
> => #<Object:0xb7d74fbc>
> >> a
> => #<Object:0xb7d74fe4>
> >> b
> => #<Object:0xb7d74fd0>
> >> c
> => #<Object:0xb7d74fbc>
> --
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