Ruby | Safe Navigation Operator

Ruby | Safe Navigation Operator

&., called “safe navigation operator”, allows to skip method call when receiver is nil. It returns nil and doesn't evaluate method's arguments if the call is skipped. The operator first appeared in Ruby 2.3.

For instance, consider the Person class:

class Person
  attr_accessor :name, :address, :phone

  def initialize(name, address, phone)
    @name = name
    @address = address.present? ? OpenStruct.new(address) : nil
    @phone = phone
  end
end

Let us fetch address using try:

> person = Person.new('Elon Musk', {}, 4240967453)
# address is `nil` for the object created
> person.address
 => nil 

> person.address.city
 => NoMethodError (undefined method `city` for nil:NilClass)

> person.address.try(:city)
 => nil

Now replace try with safe navigation operator:

> person.address&.city
 => nil
# if person object is nil, 
# the above line can be modified as follows
> person&.address&.city
 => nil

Though it takes a bit to get used to &., it's a powerful element to have under your belt.

Reference:

ruby-doc.org/core-2.6/doc/syntax/calling_me..