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?
-------------------------------------------------------|
~ Ari
crap my sig won’t fit
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.
Your problem likely results from the scoping rules for local
variables. I think it would work as you expect if you used global or
instance variables. However, for this kind of thing, I usually prefer
a hash. You might consider using something like:
WORDS = %w(yea cool awesome stuff)
DICTIONARY = {}
WORDS.each { |w| DICTIONARY[w.to_sym] = w }
DICTIONARY[:cool] # => “cool”
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.
My current method (which FAILS) is using eval
array.each {|item| eval(item + “=”#{item}"") }
When the eval is run, you’re in the context of the block. If the
variable exists beforehand, you can use it. Otherwise, I don’t know if
it can be done.
You can try to make an accessor method, though :
[ ‘a’, ‘b’, ‘c’ ].each do |t| eval <<-EOE
def #{t}
‘#{t}’
end
EOE
end
puts a
puts b
On the other hand, you can always use instance variables, with the
following code for instance :
[ ‘a’, ‘b’, ‘c’ ].each do |t|
self.instance_variable_set("@#{t}".to_sym, t)
end
puts @a
puts @b
In some contexts, I guess you could also call attr_accessor to generate
the accessors, but I can’t wrap my mind around it at this hour…
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.
There are various issues to your approach, namely that you cannot
reference local variables that are defined in an eval block and not
defined in the code around it. Ruby needs to read the variable name
literally if you want do access it. You cannot do something like
some_magic_that_sets_x()
puts x
Your probably is probably better solved by either using a Hash or
using OpenStruct.