سؤال

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"
local_variables # => [:_]
eval "t"
# => NameError: undefined local variable or method `t' for main:Object
local_variables << "t".to_sym # => [:_, :t]
t
# => NameError: undefined local variable or method `t' for main:Object
هل كانت مفيدة؟

المحلول 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

نصائح أخرى

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 could set instance variables like this:

instance_variable_set(:@a, 2)
@a
#=> 2
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top