Safe Navigation Operator (&.)

Safe Navigation Operator (&.)

&., is called "safe navigation operator", as it allows to skip method call when the receiver is nil. It returns nil and doesn't evaluate the method's arguments if the call is skipped.

&., this operator is intended to shorten the conditional statements such as object && object.property && object.method can be written as object&.property&.method.

To be clear let's view one example of a safe navigation operator;

There is a book object with an article property and you want to find the author_name from the articles. To program safely to avoid nil errors we would use something like this:

if book && book.articles && book.articles.author_name
    book.articles.author_name
end

The safe navigation operator shortens this condition. Instead, we can write

if book&.articles&.author_name
    book.articles.author_name
end

The safe navigation operator does not have exactly the same behavior as the chained conditional. Using the chained conditional (first example), the if block would not be executed if, say articles were false. The safe navigation operator only recognizes nil values but permits values such as false.

if the articles are false, will yield an error:

book&.articles&.author_name
=> undefined method 'articles' for false:FalseClass

There might be many more uses of safe navigation operators, I have outlined only one example.