method
try
v3.2.1 -
Show latest stable
- Class:
NilClass
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)
1Note
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 .