Difference between ‘&&’ and ‘and’ and ‘||’ and ‘or’ in ruby

The difference between && and and and || and or in Ruby is in the order of precedence. Operator && has a higher precedence than and. But this is generally not an issue unless used with operators which are in between these two, like the ternary and assignment operators.

Let me illustrate with an example

> s = true and false
=> false

The statement returned 1, but let us see what is the value of s

> s
=> true

Now this might come as a little surprise!

What really happened is that the assignment happened first, and then the “and” condition was checked.

Let us have a look at another potentially dangerous scenario.

> s = true and true ? 1 : 0
=> 1

The statement returned 1, but let’s see what is the value of s.

> s
=> true

Same is the case with the “or” operator. So the thumb rule is, never use and and or with ternary and assignment operators unless it is a special case and you know what you are doing.

Santhosh Kattissery is a senior consultant at Compassites. He is a web developer with hands on experience in all phases of development, from requirements gathering, database design, development, testing and deployment. He specializes in open source technologies like Ruby on Rails, JQuery, Mongodb & MySql. Prior to Compassites he has worked as a contractor for internet giants like Google and LinkedIn.

Leave a comment