如何在Ruby中动态创建局部变量?

我试图使用eval在Ruby中动态创建局部变量并改变局部变量数组。 我在IRB这样做。

 eval "t = 2" local_variables # => [:_] eval "t" # => NameError: undefined local variable or method `t' for main:Object local_variables < [:_, :t] t # => NameError: undefined local variable or method `t' for main:Object 

您必须使用正确的绑定 。 例如,在IRB中,这将起作用:

 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 

您必须使用相同的绑定对象同步评估。 否则,单个评估有其自己的范围。

 b = binding eval("t = 2", b) eval("local_variables", b) #=> [:t, :b, :_] eval("t", b) # => 2 b.eval('t') # => 2 

您可以像这样设置实例变量:

 instance_variable_set(:@a, 2) @a #=> 2