0035 Safe_navigation

Reduce the « 1 billion dollar mistake »!

Ruby 2.3 introduces the « safe navigation operator » &.. It allows you to chain methods without risking an undefined method ‘xx’ for nil (NoMethodError). This code is almost equivalent to the version with &&

0035-safe_navigation_1.png

Almost equivalent, because the « safe navigation operator » short-circuits the method call only if the receiver is nil. But false is not nil!

0035-safe_navigation_2.png

When you chain several methods, you’ll need to set it for each call if you start using it (in 99% of cases).

0035-safe_navigation_3.png

Link to Ruby documentation for the safe navigation operator.