如何在Ruby中動態創建局部變量?

[英]How do I dynamically create a local variable in Ruby?


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在Ruby中動態創建局部變量並改變局部變量數組。我在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

3 个解决方案

#1


10  

You have to use the correct binding. In IRB for example this would work:

您必須使用正確的綁定。例如,在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

#2


15  

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

#3


9  

You could set instance variables like this:

您可以像這樣設置實例變量:

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/07/24/7257f0766f6bbd558648567e6466a97c.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com