skip to content

In Rails, how do Active Support's try and try! differ, and when is Ruby's safe navigation operator &. the better choice?

level: middleimportance: should knowfreq 45%

answer

  1. both return nil on a nil receiver
  2. try: nil if the method is missing
  3. try!: NoMethodError if the method is missing
  4. private methods count as missing for try
  5. &. is Ruby syntax since 2.3

basics

~20 s

Both return nil when the receiver is nil. try also returns nil when a non-nil receiver lacks the public method; try! raises NoMethodError then. Ruby's &. behaves like try!, so prefer &. and keep try for duck-typed receivers.

solid answer

~40 s

`try(:name)` calls the public method when the receiver responds to it and returns `nil` when it does not, and `nil.try(...)` is always `nil`, even for `to_i`. `try!(:name)` is also `nil` on `nil`, but on any other receiver it uses `public_send`, so a missing method raises `NoMethodError`. Ruby's `&.` has the same contract as `try!`: skip on `nil`, otherwise call normally. That is why `&.` is the usual choice today: it is core Ruby, needs no Active Support and fails loudly on a typo, whereas `invitation.try(:guset_name)` silently returns `nil` forever. Keep `try` for the narrow case where the receiver's type genuinely varies and "does not respond" is an expected answer.

code

ruby · 11 lines
ruby
123.try(:upcase)   # => nil
123.try!(:upcase)  # NoMethodError: undefined method 'upcase'
nil.try(:to_i)     # => nil, not 0
nil&.to_i          # => nil
"rsvp".try(:upcase) # => "RSVP"

class Invitation
  private def secret_token = "abc"
end
Invitation.new.try(:secret_token)  # => nil (private looks missing)
Invitation.new.try!(:secret_token) # NoMethodError (private method)

go deeper

for a junior

Recall that try and try! both return nil on nil, and that try also returns nil when the method does not exist.

for a middle

Explain the respond_to? check behind try, why private methods look missing, and why &. has the same contract as try!.

for a senior

Argue for &. in reviews because try turns typos and type changes into silent nils, and name the cases where try is still deliberate.

for a principal

Set a team rule for nil-guarding, such as &. by default and try only for duck-typed receivers, and back it with a linter cop rather than review comments.

## The three ways to call through a possible `nil` In an invitation app, `invitation.rsvp` is `nil` until the guest answers, so `invitation.rsvp.responded_at` raises `NoMethodError` on `nil`. Rails code has three tools for this, two from **Active Support** and one from Ruby itself: | Call | Receiver is `nil` | Receiver lacks the method | Receiver has it | |---|---|---|---| | `x.try(:m)` | `nil` | `nil` | calls `m` | | `x.try!(:m)` | `nil` | raises `NoMethodError` | calls `m` | | `x&.m` | `nil` | raises `NoMethodError` | calls `m` | ## How `try` decides `try` is defined on `Object` (and on `Delegator`), with a separate `NilClass#try` that always returns `nil`. On a non-nil receiver it checks `respond_to?(method)` and only then calls `public_send`. Three consequences follow: 1. **`nil.try(:to_i)` is `nil`, not `0`.** `NilClass#try` does not ask whether `nil` responds to the method. 2. **Private methods look missing.** `respond_to?` ignores private methods by default, so `invitation.try(:secret_token)` returns `nil` instead of the value, and `try!` raises `NoMethodError` because `public_send` refuses private methods. 3. **Arguments and blocks are forwarded**, and an argument mismatch still raises `ArgumentError`: `try` only guards against a missing method, not a wrong call. Called with only a block, `try` yields the receiver unless it is `nil`, and a block that takes no argument is `instance_eval`ed instead. Because it is defined on `Object`, `try` does not exist on objects whose class inherits straight from `BasicObject`. ## Why `try` hides bugs The convenience of `try` is also its risk. Two bugs it makes silent: - **Typos.** `invitation.try(:guset_name)` returns `nil` on every call, so the page shows a blank where a name should be and no error ever reaches the logs. - **Wrong types.** If `invitation.rsvp` starts returning a `Hash` after a refactor, `try(:responded_at)` returns `nil` instead of failing, and the change goes unnoticed. `try!` keeps the nil-guard and drops the second one, and Ruby's `&.` gives the same behaviour as syntax: ```ruby invitation.rsvp&.responded_at # nil when no RSVP; raises on a typo invitation.rsvp.try!(:responded_at) # same contract, Active Support method invitation.rsvp.try(:responded_at) # also nil when rsvp lacks the method ``` ## When `try` is still the right tool `try` earns its keep where "does not respond" is a legitimate answer, not a bug: - a helper that accepts either a `Date` or a `String` and formats only what can be formatted, `value.try(:strftime, "%b %-d")`; - a polymorphic association whose targets do not all define an optional method; - older code that predates `&.` and is not worth churning. In new code, the usual review guidance is: use `&.` for nil-guarding, use `try!` only where an Active Support style call reads better, and treat a bare `try` as a deliberate statement that the method may not exist. ## Moving a codebase from `try` to `&.` A mechanical replacement is not always equivalent, so review each call: 1. If the receiver is either `nil` or an object that always defines the method, `x.try(:m)` becomes `x&.m` with no change in behaviour. 2. If the receiver can be an object that lacks the method, `&.` will now raise; decide whether that is a bug the old code was hiding or a case that needs an explicit `respond_to?` check. 3. If the method is private, `try` was returning `nil` all along; the call was probably dead code. ## What `&.` does not do `&.` is Ruby syntax, not Active Support, so it works in any Ruby program. It short-circuits only on `nil`: `false&.to_s` still calls `to_s` and returns `"false"`. It also does not make a chain safe by itself: `invitation&.rsvp.responded_at` still fails when `rsvp` is `nil`; each step that may be `nil` needs its own `&.`. And when `nil` really is impossible, neither tool belongs there: guarding a value that should always be present turns a clear crash into a blank screen. ## Summary for an interview - `try` returns `nil` for a `nil` receiver *and* for a missing or private method. - `try!` and `&.` return `nil` only for a `nil` receiver and raise otherwise. - Prefer `&.`; reach for `try` only when the method's absence is expected.

  • Why does `nil.try(:to_i)` return `nil` even though `nil.to_i` is `0`?
    Active Support defines a separate `NilClass#try` that returns `nil` without looking at the method name. The `respond_to?` check lives only in the version on `Object`, which `nil` never reaches. If you want `0`, call `to_i` directly or write `value&.to_i || 0`.
  • A code review flags `user.try(:profile).try(:city)`. What would you change it to and why?
    `user&.profile&.city`, assuming `profile` and `city` must exist when their receivers do. It keeps the nil-guard, drops the Active Support dependency and raises if either method is renamed, instead of quietly rendering a blank city. Keep `try` only where some receivers legitimately lack the method.

  • try and &. behave identically on every receiver.
  • nil.try(:to_i) returns 0 because nil responds to to_i.
  • try! raises NoMethodError when the receiver is nil.
  • try can call private methods because it uses send internally.
  • Wrapping every call in try is a good way to avoid NoMethodError in production.