Class: NilClass
Instance Method Summary collapse
-
#try(*args) ⇒ Object
It becomes specially helpful when navigating through associations that may return
nil
. - #try!(*args) ⇒ Object
-
#try?(*args) ⇒ Boolean
Calling
try?
onnil
returnsfalse
Withtry?
@person.try(:children).try(:first).try?(:has_dark_hairs?).
Instance Method Details
#try(*args) ⇒ Object
It becomes specially helpful when navigating through associations that may return nil
.
nil.try(:name) # => nil
Without try
@person && !@person.children.blank? && @person.children.first.name
With try
@person.try(:children).try(:first).try(:name)
84 85 86 |
# File 'lib/ruby-try.rb', line 84 def try(*args) nil end |
#try!(*args) ⇒ Object
88 89 90 |
# File 'lib/ruby-try.rb', line 88 def try!(*args) nil end |
#try?(*args) ⇒ Boolean
Calling try?
on nil
returns false
With try?
@person.try(:children).try(:first).try?(:has_dark_hairs?)
95 96 97 98 99 100 101 |
# File 'lib/ruby-try.rb', line 95 def try?(*args) if args.first =~ /[?]$/ false else raise ArgumentError, "For non-boolean methods use only try()" end end |