Safe navigation operator in Ruby

Ruby 2.3 has introduced safe navigation operator. Safe navigation operator returns nil if a method is called on a nil object. Before this, if a method is called on a nil object, it throws an error as given below.

$ nil.some_method
=> NoMethodError: undefined method 'some_method' for nil:NilClass
Why do we need safe navigation?

Many a times, we don’t get object because of some incorrect input values. In this case, if we proceed calling methods expecting as we have an object, the code might break if object comes up to be nil object.

To avoid such case, safe navigation is introduced. This makes sure that our code won’t break even if the object on which method is called is nil object. This should be used when we are good with receiving nil object when the method call fails.

try from activesupport

Rails has try method available provided by ActiveSupport. This method provides similar behavior. As the name suggests, it tries calling the method if the object is available. If the method is being called on nil object it returns nil instead of throwing an error.

$ nil.try(:some_method)
=> nil
safe navigation from ruby 2.3

Whenever we are unsure of object being nil object just use ampersand (&) before the method call. For example,

$ nil&.some_method
=> nil

The above code does not throw any exception and returns nil.

The above statement can also be written as following,

$ nil ? nil.some_method : nil

That means, if the object evaluates to true then, call the given method on the object. But, if the object evaluates to false then, just return nil (same) object.

try vs safe navigation

If you are working with Rails for quite some time now then, you would be very familiar and habitual of using try. If we compare the performance between try and safe navigation, safe navigation is much faster as it is supported out of the box with Ruby. It does not depend on ActiveSupport and other dependencies of Rails.