The Safe Navigation Operator (&.) in Ruby

The Safe Navigation Operator in Ruby .&

The most interesting addition to Ruby 2.3.0 is the Safe Navigation Operator(&.). A similar operator has been present in C# and Groovy for a long time with a slightly different syntax – ?.. So what does it do?

Scenario

Imagine you have an account that has an owner and you want to get the owner’s address. If you want to be safe and not risk a nil error, you would write something like the following:

ifaccount&&account.owner&&account.owner.address...end

This is really verbose and annoying to type. ActiveSupport includes the try method which has a similar behaviour (but with few key differences that will be discussed later):

ifaccount.try(:owner).try(:address)...end

It accomplishes the same thing – it either returns the address or nil if some value along the chain is nil. The first example may also return false if, for example, the owner is set to false.

Using the safe navigation operator (&.)

We can rewrite the previous example using the safe navigation operator:

account&.owner&.address

The syntax is a bit awkward but I guess we will have to deal with it because it does make the code more compact.