&. (lonely operator / safe navigation, Ruby 2.3+) gọi method chỉ khi receiver không phải nil — nếu nil thì trả về nil thay vì raise NoMethodError.
user = nil
user.name # => NoMethodError!
user&.name # => nil
user&.name&.upcase # => nil — chain dừng ngay khi gặp nil
user = User.new(name: "Alice")
user&.name # => "Alice"Khác .try (Rails):
- &. là Ruby core — bảo toàn NoMethodError nếu method không tồn tại trên object thật.
- .try nuốt cả lỗi khi method không tồn tại — có thể che giấu bug.
42.try(:nonexistent) # => nil (nuốt lỗi)
42&.nonexistent # => NoMethodError (đúng hành vi)Dùng &. trong production Ruby; dùng .try khi thực sự muốn fallback im lặng.
&. (lonely operator / safe navigation, Ruby 2.3+) calls a method only when the receiver is not nil — if nil, returns nil instead of raising NoMethodError.
user = nil
user.name # => NoMethodError!
user&.name # => nil
user&.name&.upcase # => nil — chain stops at first nil
user = User.new(name: "Alice")
user&.name # => "Alice"Difference from .try (Rails):
- &. is Ruby core — still raises NoMethodError if the method doesn't exist on a real object.
- .try silences the error even when the method doesn't exist — can hide bugs.
42.try(:nonexistent) # => nil (error swallowed)
42&.nonexistent # => NoMethodError (correct behaviour)Use &. in production Ruby; use .try only when a truly silent fallback is desired.