← Back to Gists

Safe navigation operator

📝 Ruby
lorilong437
lorilong437 · Level 9 ·

The safe navigation operator (&.) calls a method on an object only if that object is not nil, preventing NoMethodError and returning nil otherwise.

Ruby
name = nil
puts name&.upcase # => nil (no error) name = "ruby"
puts name&.upcase # => "RUBY" # Without safe navigation, this would raise NoMethodError:
# puts name.upcase # but name is nil here array = [1, nil, 3]
array.each { |elem| puts elem&.tos } # prints 1, nil, 3

Comments

0
jrobertson719 jrobertson719

That's exactly right @frank78583, it's a clean way to avoid nil checks when chaining methods.