This is just fine:
def foo
a or b
end
This is also fine:
def foo
return a || b
end
This returns void value expression
:
def foo
return a or b
end
Why? It doesn't even get executed; it fails the syntax check. What does void value expression
mean?
From a similar question I previously asked, Stefan explained in a comment that the
or
andand
are actually control flow operators and should not be used as boolean operators (||
and&&
respectively).He also referenced an article that explains the reasoning behind these control flow operators:
They provide the following examples:
and
The goal is to assign a number to
foo
and reassign it with half of its value. Thus theand
operator is useful here due to its low precedence, it modifies/controls what would be the normal flow of the individual expressions:It can also be used as a reverse
if
statement in a loop:Which is equivalent to:
or
If the first expression fails, execute the second one and so on:
It can also be used as a:
Which is equivalent to:
Therefore as sawa explained the
a or b
expression in:Has lower precedence than
return a
which, when executed, escapes the current context and does not provide any value (void value). This then triggers the error (repl.it execution):This answer was made possible due to Stefan comments (thank you).
return a or b
is interpreted as(return a) or b
, and so the value ofreturn a
is necessary to calculate the value of(return a) or b
, but sincereturn
never leaves a value in place (because it escapes from that position), it is not designed to return a valid value in the original position. And hence the whole expression is left with(some_void_value) or b
, and is stuck. That is what it means.Simply because
or
has lower precedence than||
which meansreturn a
will be executed beforeor b
,or b
is therefore unreachable