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?
On
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.
On
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.
oris very loose, it has the lowest priority. The||operator is very strong, the opposite of that. Note how in that table||comes before=, butorcomes after? That has implications.From your example:
This is how Ruby interprets this:
As such, the entire statement returns
truebutcomp1is assignedfalsebecause it doesn't capture the whole thing.So to fix that, just use the strong binding version: