Difference between "or" and || in Ruby? [duplicate]
Solution 1:
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
.
Solution 2:
As the others have already explained, the only difference is the precedence. However, I would like to point out that there are actually two differences between the two:
-
and
,or
andnot
have much lower precedence than&&
,||
and!
-
and
andor
have the same precedence, while&&
has higher precedence than||
In general, it is good style to avoid the use of and
, or
and not
and use &&
, ||
and !
instead. (The Rails core developers, for example, reject patches which use the keyword forms instead of the operator forms.)
The reason why they exist at all, is not for boolean formulae but for control flow. They made their way into Ruby via Perl's well-known do_this or do_that
idiom, where do_this
returns false
or nil
if there is an error and only then is do_that
executed instead. (Analogous, there is also the do_this and then_do_that
idiom.)
Examples:
download_file_via_fast_connection or download_via_slow_connection
download_latest_currency_rates and store_them_in_the_cache
Sometimes, this can make control flow a little bit more fluent than using if
or unless
.
It's easy to see why in this case the operators have the "wrong" (i.e. identical) precedence: they never show up together in the same expression anyway. And when they do show up together, you generally want them to be evaluated simply left-to-right.