Difference between "or" and || in Ruby?
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.
Solution 3
and
/or
are for control flow.
Ruby will not allow this as valid syntax:
false || raise "Error"
However this is valid:
false or raise "Error"
You can make the first work, with ()
but using or
is the correct method.
false || (raise "Error")
Solution 4
puts false or true
--> prints: false
puts false || true
--> prints: true
Solution 5
The way I use these operators:
||, &&
are for boolean logic. or, and
are for control flow. E.g.
do_smth if may_be || may_be
-- we evaluate the condition here
do_smth or do_smth_else
-- we define the workflow, which is equivalent to
do_smth_else unless do_smth
to give a simple example:
> puts "a" && "b"
b
> puts 'a' and 'b'
a
A well-known idiom in Rails is render and return
. It's a shortcut for saying return if render
, while render && return
won't work. See "Avoiding Double Render Errors" in the Rails documentation for more information.
Related videos on Youtube
Alex Baranosky
Check me out on Github too: https://github.com/alexbaranosky
Updated on November 23, 2020Comments
-
Alex Baranosky over 3 years
What's the difference between the
or
and||
operators in Ruby? Or is it just preference?-
Andrew Marshall almost 12 yearsSee also Difference between
and
and&&
. -
Stefan over 4 yearsFor the semantics, see Avdi Grimm's Using โandโ and โorโ in Ruby
-
-
tfwright over 14 yearsI don't know if "good practice" is on the side of the or operator. The case is analogous to parens on arguments. Method calls often read nicer without, but they lead to strange bugs in certain cases. I used to selectively use or and drop parens, but eventually I just gave up on them because fairly often they could not be used, some of those times I forgot and introduced a bug, and came to prefer the consistency of just always using parens and ||. The situation is at least debatable.
-
klochner over 14 yearsyou mean it's a matter of syntax :) they both have the same semantic interpretation (modulo operator precedence)
-
ephemient over 14 yearsThis occasionally trips me up because in Perl,
and
does have higher precedence thanor
, reflecting&&
and||
. But usually you shouldn't chain long, complex series of these together anyways. -
Jรถrg W Mittag over 14 yearsInteresting, I didn't know that. I've never actively used Perl, nor learned it.
-
klochner over 14 yearsGood answer - I didn't know about the equal precedence thing, sounds like an accident waiting to happen.
-
Marnen Laibow-Koser over 12 yearsNope.
and
is always preferable to&&
unless doing complex Boolean algebra. It's more readable. -
Marnen Laibow-Koser over 12 yearsAs far as the precedence issue, if you have more than one
and
oror
without parentheses, your code won't be readable anyway and you should refactor it. -
Marnen Laibow-Koser over 12 yearsIn short, Jörg, you're wrong here.
if this_condition or that_condition
isn't Boolean algebra except in the most pedantic sense; rather, it's control flow and so is perfectly acceptable. -
Marnen Laibow-Koser over 12 yearsIf you are relying on precedence for Boolean arithmetic, then your code isn't readable anyway. Add parentheses or refactor.
-
Yarin over 10 yearsDON'T listen to @MarnenLaibow-Koser - This has nothing to do with readability and everything to do with the fact that the precedence difference will yield different results in the most basic boolean operations: e.g.
true && false
!=true and false
,false or true
!=false || true
. -
Marnen Laibow-Koser over 10 years@Yarin Precedence only becomes an issue when you start nesting operations without parentheses. Your example of
true && false
is in fact basically equivalent totrue and false
, because there's no precedence issue. Likewise,(x > 1) and (x < 4)
is operationally equivalent to(x > 1) && (x < 4)
, because all the precedence is done with parens. In these cases, the choice is solely a readability issue. -
Marnen Laibow-Koser over 10 years@Yarin Actually, your example doesn't show what you seem to think it does.
true && false
is equivalent totrue and false
. The differences in your example are solely due to implicit precedence issues:print true and false
is equivalent toprint(true) and false
, whereasprint true && false
is equivalent toprint(true && false)
. You've proved my point rather nicely -- that precedence only comes into play when you meet operations without parentheses. -
Marnen Laibow-Koser over 10 years@Yarin Apparently I was half-wrong here; it seems that
print(true and false)
is a syntax error, which I hadn't been aware of. -
Eadz about 10 yearser wondering why this got downvoted. The 2nd top answer states "the only difference is the precedence" but by my example you can see that is not the case.
-
Mark Amery over 9 yearsThis does indeed seem to clearly demonstrate that the accepted answer is (very slightly) wrong. Is the behaviour you demonstrate here documented anywhere, to your knowledge?
-
bluehallu almost 8 yearsThe fact that it's invalid syntax is a consequence of the operator precedence. raise doesn't return therefor it can't be evaluated as an expression.
-
Anwar over 7 yearsNo. It's not true.
a = false or true
, there a will be assignedfalse
. -
Paul Brunache over 6 yearsThat's if you're you're passing it to a method. By itself it always returns true
-
DarkWiiPlayer about 6 yearsI strongly disagree with that;
and
andor
do have their place in control flow; for example, you can writeif a==b and c==d
and you can be sure thatand
has the lowest precedence. It also looks way nicer to people from outside the C world. -
jayqui almost 5 yearsThank you for explaining the point of the
or
operator :) -
PJP over 4 yearsThis should be a comment, not an answer.