Shownotes
Ruby's safe navigation operator
Chapters
- 0:00 Stop Writing nil Guards
- 0:58 Where it fits well
- 1:31 One Thing to Remember
- 1:47 Ruby's &. operator
Transcript
Stop Writing nil Guards
You have a method chain that blows up when one object in the middle is nil. You could add an if-check, or you could use the safe navigation operator and write less code. This pattern shows up everywhere. You nest conditions just to make sure nothing is nil before you call the next method. It works, but it is noisy and easy to get wrong. The ampersand-dot operator does the same thing in one line. If the receiver is nil at any point in the chain, the whole expression short-circuits and returns nil instead of raising. Think of it as a chain of gates. Each ampersand-dot checks whether the left side is nil. The moment one gate finds nil, the rest of the chain is skipped entirely. Calling a method on nil raises a NoMethodError. With ampersand-dot, you get nil back instead. That is the whole trade-off, and usually nil is exactly what you want.
Where it fits well
It is most useful when nil is a legitimate, expected state. Optional belongs-to associations, decorators that may not exist, parsed API data where a key might be missing. One thing to watch: ampersand-dot only guards against nil, not false. It is not a replacement for the double-pipe fallback pattern, though you can combine them. It also works before a block call and on the right side of an assignment. You can use it anywhere you would normally call a method.
One Thing to Remember
Use ampersand-dot when nil is a valid, expected absence. If nil at that point in your code would be a bug, let it raise so you can find the bug. Safe navigation is for expected optionality, not for silencing errors.