What does &. mean in Ruby?
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.
user&.name # nil if user is nil
user&.address&.city # nil if either is nil
list&.first&.upcaseWithout it:
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
city = user&.address&.city || "Unknown"#It works with arguments and assignment
logger&.info("started")
config&.timeout = 30#Do not chain it defensively
order&.customer&.address&.country&.codeIf 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:
data.dig(:user, :address, :city)#Rails has try, which is not the same
user.try(:name) # also nil if the METHOD does not exist
user&.name # raises if user exists but has no name methodtry swallowing typos is exactly the behaviour you do not want. Prefer &..