class Object
def try(*a, &b)
--
@person.try { |p| "#{p.first_name} #{p.last_name}" }
Without a method argument try will yield to the block unless the receiver is nil.
@people.try(:collect) {|p| p.name}
Person.try(:find, 1)
+try+ also accepts arguments and/or a block, for the method it is trying
@person.try(:name)
With +try+
@person ? @person.name : nil
or
@person && @person.name
Without +try+
==== Examples
delegate +try+ to target instead of calling it on delegator itself.
subclasses of +BasicObject+. For example, using try with +SimpleDelegator+ will
Please also note that +try+ is defined on +Object+, therefore it won't work with
If try is called without a method to call, it will yield any given block with the object.
and +nil+ will be returned instead, if the receiving object is a +nil+ object or NilClass.
*Unlike* that method however, a +NoMethodError+ exception will *not* be raised
and/or the block specified, just like the regular Ruby Object#send does.
Invokes the method identified by the symbol +method+, passing it any arguments
def try(*a, &b) if a.empty? && block_given? yield self else __send__(*a, &b) end end