It is really hard to google this, because neither || nor 'or' are good words to search for :)
I am wondering if there is a difference between the two, or if it is just a matter of preference?
It is really hard to google this, because neither || nor 'or' are good words to search for :)
I am wondering if there is a difference between the two, or if it is just a matter of preference?
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 the ruby operator precedence table.
See this question for another example using and
/&&
.
Just to add to mopoke's answer, it's also a matter of semantics. or
is considered to be a good practice because it reads much better than ||
.
As the others have already explained, the only difference is the precdence. However, I would like to point out that there are actually two differences between the two:
and
, or
and not
have much lower precedence than &&
, ||
and !
and
and or
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.