And/&& 的运算符优先级在红宝石中
我有一个关于 Ruby 中的 and/&&/= 关键字的问题。
ruby 文档说上述关键字的优先级是:(1)&&、(2)=、(3)and。
我写了这段代码:
def f(n)
n
end
if a = f(2) and b = f(4) then
puts "1) #{a} #{b}"
end
if a = f(2) && b = f(4) then
puts "2) #{a} #{b}"
end
输出是:
1) 2 4 [预期]
2) 4 4 [为什么?]
由于某种原因使用 &&导致 a 和 b 的计算结果都为 4?
I have a question regarding the and/&&/= keywords in Ruby.
The ruby docs say that the precedence for the mentioned keywords is: (1)&&, (2)=, (3)and.
I have this snippet of code I wrote:
def f(n)
n
end
if a = f(2) and b = f(4) then
puts "1) #{a} #{b}"
end
if a = f(2) && b = f(4) then
puts "2) #{a} #{b}"
end
The output is:
1) 2 4 [Expected]
2) 4 4 [Why?]
For some reason using the && causes both a and b to evaluate to 4?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不太明白你问的问题。我的意思是,在提出问题之前,您已经自己给出了答案:
&&
比=< 绑定更紧密/code> 而
and
的结合不如=
紧密。因此,在第一种情况下,表达式的计算如下:
在第二种情况下,计算如下:
I don't quite understand the question you are asking. I mean, you have already given the answer yourself, before even asking the question:
&&
binds tighter than=
whileand
binds less tightly than=
.So, in the first case, the expression is evaluated as follows:
In the second case, the evaluation is as follows:
原因很简单:优先。正如你所说,顺序是:
由于
&&
优先于=
,因此该语句的计算方式如下:其结果是:
When
x
andy
是整数,x && y
返回y
。因此2 && 4
结果为a = 4
。为了进行比较,第一个的评估如下:
The reason is simple: precedence. As you say, the order is:
Since
&&
has precedence over=
, the statement is evaluated like this:Which results in:
When
x
andy
are integers,x && y
returnsy
. Thus2 && 4
results ina = 4
.For comparison's sake, the first one is evaluated like this:
从 Ruby 编程 1.9 开始:
From Programming Ruby 1.9:
我不知道在这种情况下可以提供帮助的具体规则,但让我们使用操作的优先级。
使用优先级规则,我们可以将第二个表达式的计算分为几个步骤
。 显然,在步骤 2 中我们得到了一个不正确的情况 - = 的左侧是右值 - 临时对象,它不能被分配任何值。我假设语法分析器在遇到这种情况时违反了表达式优先级评估的规则。
有关表达式计算的更多详细信息,请参阅此处
I do not know the specific rules that can help in this situation, but let's use the priorities of operations.
Using the rules of priorities, we can divide the computation of the second expression on several steps
Obvious that in Step 2 we get an incorrect situation - on the left side of = is rvalue - temporary object, which can not be assigning by any value. I assume that syntactic analyzer break the rules of priority evaluation of expressions when encounter such situations.
More details on the calculations of expressions can be found here
如果您像这样修改代码,您将得到您期望的结果
1) 2 4
2) 2 4
if you modify your code like this you will get what you expect
1) 2 4
2) 2 4