Ruby 2.3.0 has a safe navigation operator

Updated . Posted . Visible to the public.

As announced before, Ruby has introduced a safe navigation operator with version 2.3.0. receiver&.method prevents NoMethodErrors 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.

Dominik Schöler
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2016-07-12 12:07)