Ruby logical operator
This has to do with the strength of operator binding, as operators are applied in a very specific order .
or
very loose, it has the lowest priority. The operator is ||
very strong, on the contrary. Notice how this table ||
precedes =
but or
appears after? This has consequences.
In your example:
comp1 = a > 42 or b == 60
This is how Ruby interprets it:
(comp1 = (a > 42)) or (b == 60)
So the whole statement returns true
, but gets comp1
assigned false
because it doesn't capture the whole thing.
So, to fix this, just use the strong version of the binding:
comp1 = a > 42 || b == 60
# => true
source to share
This is all related to operator priority. or
has a lower priority than =
, therefore
comp1 = a > 42 or b == 60
performed as
(comp1 = a > 42) or (b == 60)
You need to enforce the parenthesis precedence. Or be a good ruby โโcoder and never use and/or
(use &&
/ instead ||
)
* never if you don't know what you are doing. Rule of thumb: & / || for logical operations and / or for control flow.
source to share
In Ruby, the assignment to ( =
) takes precedence over the written statement or
, so the first line is interpreted like this:
(comp1 = a > 42) or (b == 60)
This means that comp1
a value is being assigned a > 42
, which is obviously false. The parenthesis in the second expression fixes the problem.
In general, in Ruby, you use ||
instead or
and also &&
instead of and
.
source to share