【发布时间】:2019-06-09 21:17:56
【问题描述】:
给定以下代码:
a = true # let's assign `a` a value
# and let's test if calling `b`, an unassigned variable, throws an error
begin
puts "The value of b is: #{b.inspect}"
rescue NameError => e
puts "Caught an error: #{e}"
end
a || b = true # the assignment should never be executed because `a` is `true`
puts "The value of b is: #{b.inspect}" # will calling `b` still raise an error?
我们得到以下结果:
Caught an error: undefined local variable or method `b' for main:Object
The value of b is: nil
尽管我们预计第二次调用 b 会引发错误,但我们看到 b 现在实际上是 nil。
这是为什么呢?为什么b 被分配nil?由于|| 从未完成分配,我希望b 保持未定义。如何定义它,但没有赋值?
【问题讨论】: