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?
try
method seems to function like the&
I would guess they implemented very similarly:inc.try(:itself) #=> 1
. You can view thetry
source here github.com/rails/rails/blob/… – Misapprehend(x = inc; x.itself unless x.nil?)
as a pre-2.3 equivalent. I'm hoping there's something less verbose. ActiveSupport'stry
may end up replicating a lot of the&.
functionality, but it's not a direct equivalent. – Showboat&.
is not equivalent toobj && obj.foo
, but in most cases it is. u&.profile reminds us as short form of u && u.profile. says Matz in bugs.ruby-lang.org/issues/11537#note-42. – Goble