Ruby difference between &&, ||, and, or
As you may know in Ruby you can use boolean operators like:
&&, ||, !
additionally there are:
and, or, not
operators.
At first glance they are just synonyms of each other. But if look deeper there are slightly differences between them:
1. You cannot overwrite/overload operators &&, ||
but you can do this with and, or
2. More important difference is that &&, ||, !
operators have different precedence then and, or, not
.
What does it mean in practice? Some examples:
#example 1
true || false && false #=> true
#example 2
true or false and false #=> false
Those simple expressions look same, but results are different. Reason of it is different order of boolean checks. In first example &&
has higher precedence then ||
, at first glance is fired check false && false
and result of it is checked with ||
. In second example boolean operators have same precedence, so boolean check is done from left to right what gives different result.
One more short example:
#example 3
a = true and b = a #=> true
puts a, b #=> true
true
#example 4
x = true && y = x #=> nil
puts x, y #=> nil
nil
Again different results because of different precedences of operators - &&
has higher and and
has lower to =
. In example 3 firstly assignment had been made and after check with and
, in example 4 in opposite way firstly boolean check was made. To make example 4 working as example 3 there is a need to introduce parenthesis:
(x = true) && (y = x) #=> true
puts x, y #=> true
true