How to dynamically create a local variable?

You cannot dynamically create local variables in Ruby 1.9+ (you could in Ruby 1.8 via eval):

eval 'foo = "bar"'
foo  # NameError: undefined local variable or method `foo' for main:Object

They can be used within the eval-ed code itself, though:

eval 'foo = "bar"; foo + "baz"'
#=> "barbaz"

Ruby 2.1 added local_variable_set, but that cannot create new local variables either:

binding.local_variable_set :foo, 'bar'
foo # NameError: undefined local variable or method `foo' for main:Object

This behavior cannot be changed without modifying Ruby itself. The alternative is to instead consider storing your data within another data structure, e.g. a Hash, instead of many local variables:

hash = {}
hash[:my_var] = :foo

Note that both eval and local_variable_set do allow reassigning an existing local variable:

foo = nil
eval 'foo = "bar"'
foo  #=> "bar"
binding.local_variable_set :foo, 'baz'
foo  #=> "baz"

Leave a Comment