Question
This question already has answers here :
[Difference between "and" and && in Ruby?](/questions/1426826/difference- between-and-and-in-ruby) (9 answers)
Closed 4 years ago.
What's the difference between the or
and ||
operators in Ruby? Or is it
just preference?
Answer
It's a matter of operator precedence.
||
has a higher precedence than or
.
So, in between the two you have other operators including ternary (? :
) and
assignment (=
) so which one you choose can affect the outcome of statements.
Here's a ruby operator precedence table.
See [this question](https://stackoverflow.com/questions/1840488/ruby-operator-
precedence-and) for another example using and
/&&
.
Also, be aware of some nasty things that could happen:
a = false || true #=> true
a #=> true
a = false or true #=> true
a #=> false
Both of the previous two statements evaluate to true
, but the second sets
a
to false
since =
precedence is lower than ||
but higher than or
.