And/&&的运算符优先级在Ruby中 [英] Operator precedence for And/&& in Ruby
问题描述
我对Ruby中的and/&&==关键字有疑问.
I have a question regarding the and/&&/= keywords in Ruby.
ruby文档说,提到的关键字的优先级是:(1)&&,(2)=,(3)和.
The ruby docs say that the precedence for the mentioned keywords is: (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 [预期]
1) 2 4 [Expected]
2)4 4 [为什么?]
2) 4 4 [Why?]
出于某些原因使用&&导致a和b的值都等于4?
For some reason using the && causes both a and b to evaluate to 4?
推荐答案
我不太了解您要问的问题.我的意思是,您已经已经给出了答案,之前甚至问了一个问题:&&
的绑定比=
紧密,而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 =
while and
binds less tightly than =
.
因此,在第一种情况下,表达式的计算方式如下:
So, in the first case, the expression is evaluated as follows:
( a=f(2) ) and ( b=f(4) )
( a= 2 ) and ( b=f(4) )
2 and ( b=f(4) ) # a=2
2 and ( b= 4 ) # a=2
2 and 4 # a=2; b=4
4 # a=2; b=4
在第二种情况下,评估如下:
In the second case, the evaluation is as follows:
a = ( f(2) && ( b=f(4) ) )
a = ( 2 && ( b=f(4) ) )
a = ( 2 && ( b= 4 ) )
a = ( 2 && 4 ) # b=4
a = 4 # b=4
4 # b=4; a=4
这篇关于And/&&的运算符优先级在Ruby中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!