Object#try
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
| Parameter | Type | Description |
|---|---|---|
| method_name | Symbol or String | The name of the method to call |
| *args | Array | Arguments to pass to the method |
| &block | Block | A 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
-
Handling potentially nil objects: Avoid explicit nil checks when calling methods on objects that might be nil.
-
Working with dynamic attributes: Call methods that may or may not exist based on the object class or configuration.
-
Chained method calls: Safely navigate through nested associations where intermediate objects might be nil.
Edge Cases and Gotchas
-
Calling
tryonnilalways returnsnil— this is the main feature, not a bug. -
Private methods: By default,
trydoes not call private methods. Usetry!or pass the method as a string to access private methods in some cases. -
NoMethodErrorvsnil: If you want an error to be raised when the method does not exist, usetry!instead. -
Performance:
tryusesrespond_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