Ruby:方法莫名其妙地被覆盖并设置为nil [英] Ruby: method inexplicably overwritten and set to nil

查看:106
本文介绍了Ruby:方法莫名其妙地被覆盖并设置为nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我执行以下红宝石代码:

If I execute this ruby code:

def foo
  100
end

p defined?(foo), foo
if false
  foo = 200
end
p defined?(foo), foo

我得到的输出是:

"method"
100
"local-variable"
nil

有人可以向我解释为什么不执行if后将foo设置为nil的原因吗?这是预期的行为还是红宝石错误?

Can someone explain to me why foo is set to nil after not executing the if? Is this expected behavior or a ruby bug?

推荐答案

即使在if false情况下无法访问代码,分配左侧的名称也将设置为nil.

Names on the left hand side of assignments get set to nil, even if the code can't be reached as in the if false case.

>> foo
NameError: undefined local variable or method `foo' for main:Object
...
>> if false
..   foo = 1
..   end #=> nil
>> foo #=> nil

当Ruby尝试解析裸词时,它首先查找局部变量(在Pickaxe书中有对此的引用,我现在似乎找不到该引用).由于您现在拥有一个名为foo的名称,因此它将显示nil.正如Mischa指出的那样,该方法仍可以称为foo().

When Ruby tries to resolve barewords, it first looks for local variables (there's a reference to that in the Pickaxe book, which I can't seem to find at the moment). Since you now have one called foo it displays nil. As Mischa noted, the method still can be called as foo().

这篇关于Ruby:方法莫名其妙地被覆盖并设置为nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆