'&&' and 'and' operators in Ruby

    At one interview I was asked: “when you write in Ruby, do you use the 'and' operator or two ampersand characters '&&' to denote the logical 'AND'?". In fact, by my old habit, I always put two ampersand characters '&&' and never thought about it. So he answered, they told me "Good."

    And you, not looking under cut, can clearly explain the difference between 'and' and '&&' in Ruby?


    Let's say we have the following code.
    total = user_messages.empty? and user_messages.total


    And what is the value of total ? Number of posts by user? Not! The thing is that the interpreter will read it like this:
    (total = user_messages.empty?) and user_messages.total



    So total will become true or false . This is not at all what you wanted! Why it happens? Just because there is an operator precedence table in Ruby . Having studied it, we understand that you can use the && operator .
    The next two lines of code are exactly the same.

    total = user_messages.empty? && user_messages.total
    total = (user_messages.empty? && user_messages.total)



    A similar story with the operators or and || .
    Take a closer look at your code ...

    PS And here's another example for final understanding (or misunderstanding)
    irb(main):001:0> x=1
    => 1
    irb(main):002:0> y=2
    => 2
    irb(main):003:0> x || y && nil
    => 1
    irb(main):004:0> x or y and nil
    => nil


    Also popular now: