method
try
v5.2.3 -
Show latest stable
- Class:
NilClass
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)
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 .