From: Todd Benson Date: 2007-07-24T06:55:24+09:00 Subject: Re: Variable Generation On 7/23/07, Ari Brown wrote: > yes, I mean spontaneously generated variables. > > Assume we have an array: > array = %w(yea cool awesome stuff) > Now, I'm looking to make a variable corresponding to the item. so that: > > yea = "yea" > cool = "cool" > awesome = "awesome" > stuff = "stuff" > > My current method (which FAILS) is using eval > array.each {|item| eval(item + "=\"#{item}\"") } > > I tested this with a puts instead of eval, and it comes out exactly > as it should. But when I try to use the variable, I get a > undefined local variable or method > error. > > Bwah? Your new variables only have scope within the block. I suppose you could do use global variables: irb> a = %w{ yea cool awesome stuff } => ["yea", "cool", "awesome", "stuff"] irb> a.each { |elem| eval("$" + elem + "=\"#{elem}\"") } => ["yea", "cool", "awesome", "stuff"] irb> $yea => "yea" Yuck. Is there some reason you couldn't just use a hash, maybe? irb> h = {} => {} irb> %w{ yea cool awesome stuff }.each { |e| h[e.intern] = e } => ["yea", "cool", "awesome", "stuff"] irb> h[:yea] => "yea" Todd