Safe navigation operator
📝 RubyThe 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
That's exactly right @frank78583, it's a clean way to avoid nil checks when chaining methods.