Ruby Language Operators Safe Navigation Operator


Ruby 2.3.0 added the safe navigation operator, &.. This operator is intended to shorten the paradigm of object && && in conditional statements.

For example, you have a House object with an address property, and you want to find the street_name from the address. To program this safely to avoid nil errors in older Ruby versions, you'd use code something like this:

if house && house.address && house.address.street_name

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

if house&.address&.street_name

The safe navigation operator doesn't have exactly the same behavior as the chained conditional. Using the chained conditional (first example), the if block would not be executed if, say address was false. The safe navigation operator only recognises nil values, but permits values such as false. If address is false, using the SNO will yield an error:

# => undefined method `address' for false:FalseClass