Ruby Language Safe Navigation Operator


Example

Ruby 2.3.0 added the safe navigation operator, &.. This operator is intended to shorten the paradigm of object && object.property && object.property.method 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
  house.address.street_name
end

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

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

Caution:
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:

house&.address&.street_name
# => undefined method `address' for false:FalseClass