Possible Duplicate:
Ruby: difference between || and ‘or’
Using Ruby
||
and
or
are very common practices which makes it important to know the difference between the two as unfortunately I am not sure.
First of all my question is if the following assumption is correct:
EX1:
if @variable_1 || @variable_2 || @variable_3
do something
else
do nothing
end
EX2:
if @variable_1 or @variable_2 or @variable_3
do something
else
do nothing
end
So in the first example if any variable is false then it will execute “do nothing”
However, for the second example all variables are checked and if one is true then it will execute “do something”.
In summary use “||” if you have a list of variables that need to be checked and if one of them returns false then a flag goes up. Use the second example with a list of variables where only one needs to be true in order to continue executing the desired code.
Are these assumptions correct?
This is false sentence.
As a result your assumptions are not correct.
Both
orand||do the same thing.The main difference is that
orhas lower precedence than||. So you should pay attention to more complex evaluations: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 compositionthere might be others too.
You can thing about the difference between those as different between
+and*:||==*andor=+. The same applies toandandnot.You should really pay attention to that.
Personally I prefer
||operator as its semantics is well understood and avoidor.While it ‘feels’ like
oris more friendly in many cases (see my code sample), even in trivial ones, it is a source of bugs.