为什么 ruby 即使它从不执行变量赋值代码也会定义变量?

Why does ruby define variables even if it never executes the variable assignment code?

给定以下代码:

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 保持未定义状态。怎么能定义了,却又不赋值呢?

一些docs解释了变量是如何创建的;据我了解,这就是解析器的工作原理:

The local variable is created when the parser encounters the assignment, not when the assignment occurs:

a = 0 if false # does not assign to a
p local_variables # prints [:a]
p a # prints nil

您可以查看其他示例:

b = true if false # b is nil
"test" || c = true # c is nil

还有其他未分配的:

puts d if false # d generates a NameError