And/&&的运算符优先级在Ruby中 [英] Operator precedence for And/&& in Ruby

查看:118
本文介绍了And/&&的运算符优先级在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屋!

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