try(*args) public

Calling try on nil always returns nil. It becomes specially helpful when navigating through associations that may return nil.

Examples

nil.try(:name) # => nil

Without try

@person && !@person.children.blank? && @person.children.first.name

With try

@person.try(:children).try(:first).try(:name)
Show source
Register or log in to add new notes.
July 24, 2012
1 thank

rest of code is in Object#try

The logic for #try is shared between this method and Object#try“Show source” here doesn’t show the whole story. Both methods are currently implemented in the file activesupport/lib/active_support/core_ext/object/try.rb .