Take the 2-minute tour ×

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

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.

share|improve this question
what is the problem that you are trying to solve? what ever you are trying to do, it's probably possible in ruby, but i don't think that this is a good thing to do. –  phoet Oct 11 '13 at 15:39
Not the same, but perhaps define_method(:foo) { 1 } is an option? –  spickermann Oct 11 '13 at 15:50
I know it involves variable scope, but I don't understand your question. –  icantbecool Oct 11 '13 at 15:50
@phoet I'm asking about the Ruby language independent of any need. The question arose in the context of another SO question. –  Peter Alfvin Oct 11 '13 at 16:35
@spickermann I agree that would be similar, but not the same. :-) –  Peter Alfvin Oct 11 '13 at 16:36
show 8 more comments

4 Answers

up vote 5 down vote accepted

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.


(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

puts local_hash['foo']
#=> 'baz'
share|improve this answer
If you'll update your answer to simply say "No, it cannot be done" and provide the Matz reference, I'll be glad to accept it. This assumes that in addition to it not being possible with eval, there is no other method to accomplish it either in light of Matz's explanation about local variables only being created at compile time. –  Peter Alfvin Oct 11 '13 at 18:23
Unfortunately I can't do that...I only know of Matz's explanation but can't tell you for sure that just because it's been stopped via eval that it can't be done via another method (other than running Ruby 1.8). So I'm OK with leaving the door open rather than being proven wrong by a master Ruby hacker :) –  Dan Nguyen Oct 11 '13 at 18:57
Ok, how about at least removing the "I'm sure there's a way" comment, in which case I'll +1 for the Matz reference. :-) While they're may be a way, I don't think there's any reason for you to "be sure" and I'd hate to give anyone false hope. On a related point, as evidenced in my comments on the question, I'm not trying to solve any underlying problem; I'm just trying to improve my understanding of the language and the core libraries. As such, your proposal involving the Hash is not really relevant and, from my point of view, would best be removed. –  Peter Alfvin Oct 11 '13 at 19:08
Done. But I hope someone proves me wrong and comes up with some clever hack, though I can't imagine what that could possibly be, given Matz's explanation –  Dan Nguyen Oct 11 '13 at 22:46
Accepted and plus 1. :-) –  Peter Alfvin Oct 11 '13 at 22:55
add comment

In the context of creating the local variable itself, it is true there are some difficulties to overcome, however assigning dynamically is still no problem.

>> my_lv = 0
=> 0
>> instance_eval("#{'my_lv'} = 42")
=> 42
>> my_lv
=> 42

So, simply create from a gathered input (from gets, chomped or stripped as needed, it will just naturally end up as a string) and call to_sym on it and stuff the new symbol into local_variables and eval away...

>> local_variables << :my_created_lv
=> [:my_lv,

Then you take the gathered string that you converted to a symbol, and assigned to in the code shown above, and eval it to get the value.

>> eval :my_lv.to_s
>> 24

As noted in another answer, I am unable to easily replicate this outside of Pry or IRB.

share|improve this answer
I'm asking about the case where the variable is not already defined. There's no issue where the variable is already defined and you just want to change the value. –  Peter Alfvin Oct 11 '13 at 21:35
That is why I used a string inside the interpolation. The rest is academic. –  vgoff Oct 11 '13 at 21:38
And only works in a REPL apparently. :( –  vgoff Oct 11 '13 at 23:16
Sorry, I didn't follow either of your last two comments. –  Peter Alfvin Oct 11 '13 at 23:19
I took the commands I wrote in the answer and wrote a normal Ruby program to attempt to verify that it still works as a normal Ruby program, rather than line by line evaluation, and it is restricted from working in a regular Ruby program. REPL means "Read - Eval - Print - Loop". The prior was just meant to say that the string inside of the interpolation could have been received via a number of ways, gets.chomp perhaps. Either way, not going to be easily defeated in with Ruby 1.9 and later. –  vgoff Oct 11 '13 at 23:33
add comment

Is there anything wrong with foo=nil?

share|improve this answer
Yes, it's not dynamic. :-) I'm asking about a mechanism for doing this at runtime (e.g. where you have a symbol representing the variable name in question and variable containing the value you want to assign). –  Peter Alfvin Oct 11 '13 at 16:34
add comment

Would a class instance variable work for you?

class Cat
Cat.instance_variable_set '@last_words', 'meow, meow, me...'
Cat.instance_variable_get '@last_words' # => "meow, meow, me..."
Cat.new.instance_variable_get '@last_words' # => nil

If not, please elaborate on the context and how you would use the local variable.

share|improve this answer
My question is independent of where the local variable resides (class, method, block, whatever). And per my earlier comment on the question itself, there is no underlying problem I'm trying to solve. I'm merely asking a question about the language and core libraries related to local variable declaration in order to better my understanding. –  Peter Alfvin Oct 11 '13 at 20:08
add comment

Your Answer


