The answers to every question I can find (Q1, Q2) regarding Ruby's new safe navigation operator (&.
) wrongly declare that obj&.foo
is equivalent to obj && obj.foo
.
It's easy to demonstrate that this equivalence is incorrect:
obj = false
obj && obj.foo # => false
obj&.foo # => NoMethodError: undefined method `foo' for false:FalseClass
Further, there is the problem of multiple evaluation. Replacing obj
with an expression having side effects shows that the side effects are doubled only in the &&
expression:
def inc() @x += 1 end
@x = 0
inc && inc.itself # => 2
@x = 0
inc&.itself # => 1
What is the most concise pre-2.3 equivalent to obj&.foo
that avoids these issues?