为什么我可以在Ruby中为自己分配一个未定义的变量并获得nil?

Nat*_*ong 6 ruby internals variable-assignment ruby-1.9.3

可能重复:
为什么a = a在Ruby中为零?

使用未定义的变量,Ruby中有一个"奇怪的现象".就像这样:

# irb session follows
#
foo        # undefined local variable or method 'foo'
bar        # same for 'bar'
foo = bar  # still same for 'bar'
foo = foo  # nil - HUH?
foo        # is now set to nil!?
Run Code Online (Sandbox Code Playgroud)

为什么我可以在Ruby中为自己分配一个未定义的变量并获取nil

请注意,我在这里使用Ruby 1.9.3.我不确定这可能是什么其他版本.

(感谢Gary Bernhardt在他热闹的演讲中证明了这一点.)

Fre*_*ung 8

bar未定义的事实实际上并不是最有趣的部分,因为例如甚至不需要尝试赋值

if false
  foo = 1
end
Run Code Online (Sandbox Code Playgroud)

将foo设置为nil.据我了解,局部变量范围是静态确定的,因为它是在没有实际运行代码的情况下确定的,仅仅通过分析它.Ruby认为赋值可能发生,因此它创建局部变量并将其设置为nil.见http://ruby.runpaint.org/variables#local


the*_*ber 2

Nil 在 Ruby 中很神奇,因为它认为一切都是对象。实际上有一个被分配的单例 nil 对象。当你这样做的时候

foo = bar
Run Code Online (Sandbox Code Playgroud)

“foo”变量突然出现,并以神奇的 nil 对象为值。在进行赋值之前,Ruby 没有办法“知道” foo 是什么(它是变量吗?方法调用?),但是一旦进行赋值,它就开始将其视为变量。