理解Ruby - 未定义的局部变量

时间:2014-02-11 14:15:28

标签: ruby variables

我一直在玩Ruby并遇到过这种奇怪的行为。有人可以告诉我为什么会这样吗?

如果我跑:

def my_fn
  if false then
    a = {:a=>10, :b=>20}
  end
  puts a.class
  a || {}
end

并打印代码成功编译的结果并返回{}。 但是,如果我将代码更改为:

def my_fn
  puts a.class
  a || {}
end

它不会返回{}但会抛出错误。 "'my_fn': undefined local variable or method 'a' for main:Object (NameError)"

不应该只是零而不会导致错误吗?

1 个答案:

答案 0 :(得分:9)

这是因为 - The local variable is created when the parser encounters the assignment, not when the assignment occurs

在第一个代码解析器中看到行a = {:a=>10, :b=>20},因此创建了一个变量,但没有发生任何赋值。因此anilAs per the all known facts a || {}返回{}

在第二个代码中,解析器没有看到a发生任何分配,因此a尚未创建为局部变量,也未创建名为a的方法。因此,当您尝试使用a时,会在报告时收到有效错误,即未定义的局部变量或方法'a'

相关问题