I'm wondering if there is a method which will allow me to dynamically define a previously undefined variable in the current context. For example:
foo # => NameError: undefined method or local variable ...
# Some method call which sets foo = 1 in the local context
foo # => 1
Put another way, given that foo is undefined, I'm looking for any code that would let me define the local variable foo without using the foo variable (e.g. if I had some other variable bar whose value was :foo and I had to rely on that to set the value of foo).
It seems that eval('foo = 1') or eval('foo = 1', binding) or, in Ruby 2.1, binding.local_variable_set(:foo, 1) are all equivalent to:
1.times do
foo = 1
end
in other words, they set foo in the context of a new local context, such that the value is inaccessible outside of that context.
Is what I'm looking to do possible?
Update: This question is not specific to any particular local variable context (module/class, method, proc, block, etc.). I'd be interested in knowing definitively any context where it can or cannot be done.