使用eval分配实例变量可以正常工作,而另一个则不然。试着了解这里发生的事情。任何帮助表示赞赏。
>> var = "a value"
=> "a value"
>> @v
=> nil
>> eval "@v = var"
=> "a value"
>> @v
=> "a value"
>> eval "var_new = var"
=> "a value"
>> var_new
NameError: undefined local variable or method `var_new' for main:Object
from (irb):7
from C:/Ruby193/bin/irb:12:in `<main>'
答案 0 :(得分:3)
eval
只有自己的范围。您可以访问之前定义的变量,但您无法访问eval
中定义的变量。
确定范围,您的示例类似于:
var = "a value"
1.times do # create new scope
new_var = var
end
new_var
# NameError: undefined local variable or method `new_var' for main:Object
答案 1 :(得分:3)
eval创建自己的范围:
>> i = 1; local_variables.count
=> 2
>> eval "j = 1; local_variables.count"
=> 3
>> local_variables.count
=> 2
答案 2 :(得分:2)
如下所示进行内省:
var = "a value"
eval "var_new = var,defined?(var_new)" #=> ["a value", "local-variable"]
defined?(var_new) #=>nil
defined?(var) #=>"local-variable"
defined?(temp) #=>nil
您只能在eval
内知道 var_new 。在eval
temp 和 var_new 之外,两者都相同。