为什么在Ruby中使用||当`a`未定义,但是a = a ||时,1将引发错误。 1不会吗? [英] Why in Ruby, a || 1 will throw an error when `a` is undefined, but a = a || 1 will not?

查看:107
本文介绍了为什么在Ruby中使用||当`a`未定义,但是a = a ||时,1将引发错误。 1不会吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果未定义 a ,则 a || 1 将引发错误,但 a = a || 1 不会。

When a is undefined, then a || 1 will throw an error, but a = a || 1 will not. Isn't that a little bit inconsistent?

irb(main):001:0> a
NameError: undefined local variable or method 'a' for main:Object
        from (irb):1
        from c:/ruby/bin/irb:12:in '<main>'

irb(main):002:0> a || 1
NameError: undefined local variable or method 'a' for main:Object
        from (irb):2
        from c:/ruby/bin/irb:12:in '<main>'

irb(main):003:0> a = a || 1
=> 1


推荐答案

a

此处,您正在评估 a ,其中未定义。因此,您会遇到异常。

Here, you are evaluating a, which isn't defined. Therefore, you get an exception.

a || 1

在这里,您仍然必须评估 a 确定布尔表达式的值。就像上面一样,未定义 a 。因此,您将获得一个例外。

Here, you still have to evaluate a to determine the value of the boolean expression. Just like above, a isn't defined. Therefore, you get an exception.

a = a || 1

此处, a 定义。它被定义为未初始化的局部变量。在Ruby中,未初始化的变量的结果为 nil ,因此赋值表达式的右侧的结果为 nil ||。 1 的结果为 1 ,因此赋值表达式的返回值为 1 ,副作用是 a 被初始化为 1

Here, a is defined. It is defined to be an uninitialized local variable. In Ruby, uninitialized variables evaluate to nil, so the right hand side of the assignment expression evaluates to nil || 1 which evaluates to 1, so the return value of the assignment expression is 1 and the side effect is that a is initialized to 1.

编辑:似乎在何时定义变量以及何时在Ruby中初始化变量时有些困惑。 get在解析时间定义,但在 runtime 初始化。您可以在这里看到它:

It seems that there is some confusion on when variables get defined and when they get initialized in Ruby. The get defined at parse time but initialized at runtime. You can see it here:

 foo # => NameError: undefined local variable or method `foo' for main:Object

foo 未定义。

if false
  foo = 'This will never get executed'
end

此时, foo 。该行永远不会执行这一事实是完全无关紧要的,因为解释器还是与此无关:本地变量是由解析器定义的,而解析器显然会看到这一行。

At this point, foo is defined, even though the line will never get executed. The fact that the line never gets executed is completely irrelevant, because the interpreter has nothing to do with this anyway: local variables are defined by the parser, and the parser obviously sees this line.

foo # => nil

没有错误,因为 foo 是定义的,并且由于未初始化,计算结果为 nil

There is no error, because foo is defined, and it evaluates to nil because it is uninitialized.

这篇关于为什么在Ruby中使用||当`a`未定义,但是a = a ||时,1将引发错误。 1不会吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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