They do the same thing, but or
has a lower precedence than ||
(and, in fact, or
has a lower precedence than most of the other operators).
Your conclusions about the examples are incorrect.
if true || true || false
puts 'something'
else
puts 'nothing'
end
This code outputs 'something' because that's how the 'logical or' operation works. It reads like "if at least one of condition1 or condition2 or condition3 are true...".
The second example is exactly the same, but only because of the rules of precedence in Ruby.
or the second example all variables are checked and if one is true then it will execute "do something".
This is false sentence.
As a result your assumptions are not correct.
Both or
and ||
do the same thing.
The main difference is that or
has lower precedence than ||
. So you should pay attention to more complex evaluations:
# Simple cases are not confusing
false || true # true
false or true # true
# This is more complex
a = false || true # a=true
a = false or true # a=false
# Also similarly as 1 + 2*3 returns 7, the following returns true:
false or false||true # true
# BUT! THIS IS IMPORTANT!
a = false or false||true # a=false
a = (false or false||true) # a=true
Here is a list of operators precedence.
So the real difference will be noticed if you use the expression that includes any of the following operators:
.. ...
- Range (inclusive and exclusive)? :
- Ternary if-then-else= %= { /= -= += |= &= >>= <<= *= &&= ||= **=
- Assignmentdefined?
- Check if specified symbol definednot
- Logical negationand
- Logical composition
there might be others too.
You can thing about the difference between those as different between +
and *
: ||
==*
and or
=+
. The same applies to and
and not
.
You should really pay attention to that.
Personally I prefer ||
operator as its semantics is well understood and avoid or
.
While it 'feels' like or
is more friendly in many cases (see my code sample), even in trivial ones, it is a source of bugs.