Operator precedence for And/&& in Ruby

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?

Answers 1

  • 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
    

Related Articles