It seems that Ruby's magic would provide a way, but according to Matz, this was only possible in 1.8 via eval
and only in certain contexts (i.e. irb
). As of 1.9, this behavior was taken out ("strictly forbidden"):
Matz himself weighs in here: https://www.ruby-forum.com/topic/155673#685906
I read from somewhere that now Ruby can't dynamically create local variable. Is it true or just a bug?
The local variables are created in compile time, so that local variables that are defined in eval() cannot be accessed outside of eval. In 1.8, irb and tryruby does line by line compilation so that local variables are spilled from eval(), but in 1.9, it's strictly prohibited even under line-by-line compilation.
matz.
(Non-sequitur alternative here, for anyone who wants something like this but not the exact technical situation that the questioner has):
Use a hash:
local_hash = {}
my_vars.each_pair do |k,v|
local_hash[k] = v
end
puts local_hash['foo']
#=> 'baz'