为什么ruby即使从不执行变量赋值代码也要定义变量? [英] Why does ruby define variables even if it never executes the variable assignment code?

查看:26
本文介绍了为什么ruby即使从不执行变量赋值代码也要定义变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下代码:

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.

Even though we expected calling b to raise an error the second time, we see that b is now, in fact, nil.

这是为什么?为什么 b 被赋值为 nil?由于 || 从未达到分配,我希望 b 保持未定义.如何定义但不赋值?

Why is that? Why does b get assigned nil? Since the || never reached the assignment, I would expect b to remain undefined. How can it be defined, but not assigned a value?

推荐答案

docs 解释了变量是如何创建的;据我了解,这就是解析器的工作方式:

Some of the docs explain how variables are created; the explanation as I understand it is that's just how the parser works:

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

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

还有其他人没有被分配:

And others it doesn't get assigned:

puts d if false # d generates a NameError

这篇关于为什么ruby即使从不执行变量赋值代码也要定义变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆