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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)