I'm trying to evaluate the expression (a=10) || (rr=20)
while the rr variable is not defined
so typing rr
in the ruby console before evaluating the previous expression returns
rr
NameError: undefined local variable or method `rr' for main:Object
from (irb):1
from :0
When I write the expression (a=10) || (rr=20)
it returns 10, and when I write rr afterwards it says nil
(a=10) || (rr=20)
rr # => nil
so, why is this happening? Shouldn't rr be defined only if the second argument of the || operator is evaluated, which should be never based on the documentation?
No while evaluating && if the first condition is false then it doesn't evaluate the second condition. Similarly while evaluating || if the first condition is true then the second condition is not evaluated.
The || operator returns the Boolean OR of its operands. It returns a true value if either of its operands is a true value. If both operands are false values, then it returns a false value. Like && , the || operator ignores its righthand operand if its value has no impact on the value of the operation.
It will evaluate from left to right and short-circuit the evaluation if it can (e.g. if a evaluates to false it won't evaluate b). If you care about the order they are evaluated in you just need to specify them in the desired order of evaluation in your if statement.
The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool .
This happens because the ruby interpreter defines a variable when it sees an assignment to it (but before it executes the actual line of code). You can read more about it in this answer.
Boolean OR (||
) expression will evaluate to the value of left hand expression if it is not nil
and not false
, else ||
will evaluate to the value of right hand expression.
In your example the ruby interpreter sees an assignment to a
and rr
(but it doesn't execute this line yet), and initializes (defines, creates) a
and rr
with nil
. Then it executes the ||
expression. In this ||
expression, a
is assigned to 10
and 10
is returned. r=20
is not evaluated, and rr
is not changed (it is still nil
). This is why in the next line rr
is nil
.
As @DOC said, &&
and ||
are known as short circuited
conditional operators.
In case of ||, if the left part of || expression returns true, the right part won't be executed.
That means the right part will be executed only if the left part of ||
expression returns false.
In case of &&, right part of the
&&expression will be executed only if left part of && returns true.
In the given scenario (a=10) || (rr=20)
, rr=20 won't be executed since the ruby expression a=10
returns true
. Note that in ruby assignment expression returns true except nil and false
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With