有人可以检查一下我注意到的这种行为吗?
如果您没有为局部变量分配任何内容并尝试将其打印出来,则会按预期生成异常。如果在无法访问的代码路径中分配局部变量,则它可以正常工作。应该是这样的吗?
def a
# Should generate an error because foobar is not defined.
puts foobar
end
def b
# This block never is run but foobar is entered into the symbol table.
if false
foobar = 123
end
# This succeeds in printing nil
puts foobar
end
begin; a; rescue Exception => e; puts "ERROR: #{e.message}"; end
begin; b; rescue Exception => e; puts "ERROR: #{e.message}"; end
答案 0 :(得分:6)
是的,这是正确的。 Ruby在解析期间范围变量,而不是在函数运行时期间。因此,简单地引用变量就足以定义它,即使它在无法访问的代码路径中被引用。
我在前一段时间遇到了这个问题 - 请参阅this blog post了解该行为。