I had an interesting question so I shared it in a test format
def ampersand_return
puts "foo" && return
puts "bar"
end
def and_return
puts "foo" and return
puts "bar"
end
> ampersand_return
=> nil
> and_return
foo
bar
=> nil
Can you explain what's happening?
As a general rule, the difference between &&
and ʻand` lies in its priority.
&& return
&&
is calculated first and is equivalent to the following
puts ("foo" && return)
Since " foo "
is truthy, return
on the right side is processed, and the method returns without outputting anything.
puts" foo "
is calculated first and is equivalent to
(puts "foo") and return
Since puts
returns nil
, the right side of ʻandis not processed, both
" foo "and
" bar "` are output, and the method ends normally.
Isn't the documentation specified about operators where method call takes precedence, as in the ʻand example? Yo According to [This Stack Overflow Answer](https://stackoverflow.com/a/42077277/3891638), ʻand
, ʻor, ʻif
, ʻunless, ʻuntil
, while
, rescue
Seems to behave this way
Recommended Posts