Ruby 2.3 has introduced safe navigation operator.
Safe navigation operator returns nil
if a method is called
if a method is called on a
it throws an error as given below.
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
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
This should be used when we are good
when the method call
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
nil object it returns
instead of throwing an error.
safe navigation from ruby 2.3
Whenever we are unsure of
just use ampersand (&) before the method call.
The above code does not throw any exception and returns nil.
The above statement can also be written as following,
That means, if the object evaluates to
call the given method on the object.
if the object evaluates to
nil (same) object.
try vs safe navigation
If you are working with Rails for quite some time now
you would be very familiar and habitual of using
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
other dependencies of Rails.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox