What does the safe navigation operator (&.) do and when would you use it?
Last updated
The safe navigation operator &. calls a method on a receiver only if it isn't nil: if the receiver is nil it short-circuits and returns nil instead of raising NoMethodError.
What it replaces: Turns
user && user.address && user.address.cityintouser&.address&.city.How it differs from
.:a&.bonly guards againstnil, not against other falsey-ish or missing methods.When to use it: Optional values that may legitimately be
nil(API results, optional associations).When NOT to use it: Don't chain it everywhere to silence bugs: it can hide a
nilthat should never occur and mask the real error.
[lang:ruby]
user&.address&.city # nil if user or address is nil
user.address.city # raises NoMethodError if either is nil
- https://shiftasia.com/community/better-null-check-with-safe-navigation-operator-in-ruby/
- https://ruby-doc.org/core-2.6/doc/syntax/calling_methods_rdoc.html
- https://thoughtbot.com/blog/ruby-safe-navigation
- https://www.reddit.com/r/ruby/comments/o7tgu5/til_the_safe_navigation_operator_in_ruby/
- https://www.mintbit.com/blog/safe-navigation-operator-vs-explicit-nil-check-which-is-better/