val1 = true and false # hint: output of this statement in IRB is NOT value of val1!
val2 = true && false
Although these two statements might appear to be equivalent, they are not, due to the order of operations. Specifically, the and
and or
operators have lower precedence than the =
operator, whereas the &&
and ||
operators have higher precedence than the =
operator, based on order of operations.
To help clarify this, here’s the same code, but employing parentheses to clarify the default order of operations:
(val1 = true) and false # results in val1 being equal to true
val2 = (true && false) # results in val2 being equal to false
This is, incidentally, a great example of why using parentheses to clearly specify your intent is generally a good practice, in any language. But whether or not you use parentheses, it’s important to be aware of these order of operations rules and to thereby ensure that you are properly determining when to employ and
/ or
vs. &&
/ ||
.