I am trying to dynamically create local variables in Ruby using eval
and mutate the local-variables array. I am doing this in IRB.
eval \"t = 2\
You could set instance variables like this:
instance_variable_set(:@a, 2)
@a
#=> 2
You have to synchronize the evaluations with the same binding object. Otherwise, a single evaluation has its own scope.
b = binding
eval("t = 2", b)
eval("local_variables", b) #=> [:t, :b, :_]
eval("t", b) # => 2
b.eval('t') # => 2
You have to use the correct binding. In IRB for example this would work:
irb(main):001:0> eval "t=2", IRB.conf[:MAIN_CONTEXT].workspace.binding
=> 2
irb(main):002:0> local_variables
=> [:t, :_]
irb(main):003:0> eval "t"
=> 2
irb(main):004:0> t
=> 2