Flowdock
try(*args) public

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

nil.try(:name) # => nil

Without try

@person && @person.children.any? && @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 .