Read more

Ruby 2.3.0 has a safe navigation operator

Dominik Schöler
July 12, 2016Software engineer at makandra GmbH

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
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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 14:07)