As announced before, Ruby has introduced a safe navigation operator with version 2.3.0. receiver&.method
prevents NoMethodError
s by intercepting method invocations on nil
.
user = User.last
user&.name # => "Dominik"
# When there is no user, i.e. user is nil:
user&.name # => nil
This might remind you of andand
, and indeed it behaves very similar. The only difference is in handling of false
, as false.andand.class
returns false
(intercepts invocation), whereas false&.class
permits the invocation.
&.
might also remind you of Rails' Object#try
. However, their scopes are different, and in Rails 4 nil
-checking is only a "side effect" of try
.
Posted by Dominik Schöler to makandra dev (2016-07-12 12:07)