Difference between "or" and || in Ruby?

Alex Baranosky picture Alex Baranosky · Jan 18, 2010 · Viewed 111.1k times · Source

What's the difference between the or and || operators in Ruby? Or is it just preference?

Answer

mopoke picture mopoke · Jan 18, 2010

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 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.