Object#try

Added in v3.1 · Updated March 13, 2026 · Core Classes
ruby rails activesupport

Object#try is an ActiveSupport extension that calls a method on an object only if the object responds to it. If the object does not respond to the method, it returns nil instead of raising a NoMethodError. This is particularly useful when working with objects that may or may not have certain methods, or when chaining method calls on objects that could be nil.

Signature

ParameterTypeDescription
method_nameSymbol or StringThe name of the method to call
*argsArrayArguments to pass to the method
&blockBlockA block to pass to the method

Code Examples

# Basic usage - call method if it exists
user = User.new(name: "John")
user.try(:name)           # => "John"
user.try(:email)          # => nil (method does not exist)

# With arguments
user.try(:format_name, :uppercase)

# With a block
user.try(:names) { |n| n.upcase }

# Safe navigation alternative
# Instead of: @user && @user.profile && @user.profile.name
@user.try(:profile).try(:name)

Common Use Cases

  1. Handling potentially nil objects: Avoid explicit nil checks when calling methods on objects that might be nil.

  2. Working with dynamic attributes: Call methods that may or may not exist based on the object class or configuration.

  3. Chained method calls: Safely navigate through nested associations where intermediate objects might be nil.

Edge Cases and Gotchas

  • Calling try on nil always returns nil — this is the main feature, not a bug.

  • Private methods: By default, try does not call private methods. Use try! or pass the method as a string to access private methods in some cases.

  • NoMethodError vs nil: If you want an error to be raised when the method does not exist, use try! instead.

  • Performance: try uses respond_to? internally, so there is a slight overhead compared to direct method calls.

Return Value

Returns the result of the method call if the object responds to the method, otherwise returns nil.

See Also

  • Object#tap — useful when you want to keep chaining while inspecting an object
  • Object#present? — returns the object if it is present, nil otherwise
  • Object#dig — safely extract nested values from hashes and arrays