Ruby:未定义的局部变量OK如果在不同的代码路径中定义?

Amy*_*Amy 3 ruby variables

有人可以检查一下我注意到的这种行为吗?

如果您没有为局部变量分配任何内容并尝试将其打印出来,则会按预期生成异常.如果在无法访问的代码路径中分配局部变量,则它可以正常工作.应该是这样的吗?

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
Run Code Online (Sandbox Code Playgroud)

Chr*_*ald 6

是的,这是正确的.Ruby在解析期间范围变量,而不是在函数运行时期间.因此,简单地引用变量就足以定义它,即使它是在无法访问的代码路径中引用的.

我曾经遇到过这个问题 - 请参阅此博客文章,了解该行为.