Safe Navigation Operator

suggest change

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:

&. does not behave exactly like &&. The && chain skips any falsy value. &. skips only nil. If house is false, the call raises undefined method 'address' for false. If house.address is false, it raises undefined method 'street_name' for false.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents