What does &. mean in Ruby?

Ruby 2 min read
Short answer

a&.b calls b only when a is not nil; otherwise the whole expression is nil. It replaces a && a.b and avoids NoMethodError on nil.

ruby
user&.name                  # nil if user is nil
user&.address&.city         # nil if either is nil
list&.first&.upcase

Without it:

ruby
user.name                   # NoMethodError: undefined method `name' for nil
user && user.name           # the old way — works, but repeats the receiver

#Only nil short-circuits it

&. checks for nil specifically, not falsiness. false&.to_s still calls to_s and returns "false".

#Combining with a default

ruby
city = user&.address&.city || "Unknown"

#It works with arguments and assignment

ruby
logger&.info("started")
config&.timeout = 30

#Do not chain it defensively

ruby
order&.customer&.address&.country&.code

If an order should always have a customer, that &. is hiding a bug — you get nil at the end with no clue which link broke. Use &. where nil is a legitimate, expected state, and let the rest raise.

#dig is often clearer

For nested hashes and arrays:

ruby
data.dig(:user, :address, :city)

#Rails has try, which is not the same

ruby
user.try(:name)      # also nil if the METHOD does not exist
user&.name           # raises if user exists but has no name method

try swallowing typos is exactly the behaviour you do not want. Prefer &..