I don't know what makes a difference here.
a = 24
b = 60
comp1 = a > 42 or b == 60
comp1 # => false
comp2 = (a > 42 or b == 60)
comp2 # => true
Could someone explain what's going on and why the return values are different?
I don't know what makes a difference here.
a = 24
b = 60
comp1 = a > 42 or b == 60
comp1 # => false
comp2 = (a > 42 or b == 60)
comp2 # => true
Could someone explain what's going on and why the return values are different?
It has all to do with operator precedence. or
has lower priority than =
, so
comp1 = a > 42 or b == 60
is executed as
(comp1 = a > 42) or (b == 60)
You need to enforce precedence by parentheses. Or be a good ruby coder and never* use and/or
(use &&
/||
instead)
* never, unless you know what you're doing. A rule of thumb is: &&/|| for logical operations, and/or - for control flow.
In Ruby, assignment (=
), has higher precedence than the written or
operator, so the first line is interpreted as this:
(comp1 = a > 42) or (b == 60)
That means that comp1
is being assigned the value of a > 42
, which is obviously false. The parenthesis in the second expression resolve the issue.
In general, in Ruby, you use ||
instead of or
, and likewise, &&
in place of and
.
This is due to the strength of the operator binding, as operators are applied in a very particular order.
or
is very loose, it has the lowest priority. The||
operator is very strong, the opposite of that. Note how in that table||
comes before=
, butor
comes after? That has implications.From your example:
This is how Ruby interprets this:
As such, the entire statement returns
true
butcomp1
is assignedfalse
because it doesn't capture the whole thing.So to fix that, just use the strong binding version: