What is the safe navigation operator (&.) and when should you use it?

Beginner

Answer

The safe navigation operator (&.) calls methods only if the receiver is not nil, preventing NoMethodError on nil objects.

user&.profile&.name  # Returns nil if any part is nil
# Equivalent to:
user && user.profile && user.profile.name

# With arrays
users&.first&.name  # Safe even if users is nil