当它实际上没有被定义时,它得到值 nil
只是因为它被“触摸”了:
$ irb
ruby-1.9.2-p0 > foo = true if !defined? foo
=> nil
ruby-1.9.2-p0 > foo
=> nil
ruby-1.9.2-p0 > if !defined? bar
ruby-1.9.2-p0 ?> bar = true
ruby-1.9.2-p0 ?> end
=> true
ruby-1.9.2-p0 > bar
=> true
所以 if
... end
按预期工作,但 foo = true if ...
没有。
最佳答案
Ruby 在执行包含赋值的行之前定义了一个局部变量,因此 defined?(foo)
对于单行代码将始终为 true
。
另一个例子显示局部变量是在行的任何部分执行之前定义的:
defined? foo # => false
foo = foo # => foo is now nil
关于Ruby 的 "foo = true if !defined? foo"不会按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3775402/