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

2024-01-10

给出以下代码:

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 https://docs.ruby-lang.org/en/2.6.0/syntax/assignment_rdoc.html#label-Local+Variables+and+Methods解释如何创建变量;据我了解,解释器就是这样工作的:

局部变量是在解析器遇到赋值时创建的,而不是在赋值发生时创建的:

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 ruby​​ 定义变量,即使它从不执行变量赋值代码? 的相关文章

随机推荐