Ruby | Safe Navigation Operator

Ruby | Safe Navigation Operator

Vishnuprasad K's photo
Vishnuprasad K
·Oct 22, 2020·

1 min read

&., 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? ? : nil
    @phone = phone

Let us fetch address using try:

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

 => 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.


Share this