sonic-pi

https://github.com/sonic-pi-net/sonic-pi

C++

Code. Music. Live.

Object#try

Invokes the public method whose name goes as first argument just like
+public_send+ does, except that if the receiver does not respond to it the
call returns +nil+ rather than raising an exception.

This method is defined to be able to write

  @person.try(:name)

instead of

  @person ? @person.name : nil

+try+ returns +nil+ when called on +nil+ regardless of whether it responds
to the method:

  nil.try(:to_i) # => nil, rather than 0

Arguments and blocks are forwarded to the method if invoked:

  @posts.try(:each_slice, 2) do |a, b|
    ...
  end

The number of arguments in the signature must match. If the object responds
to the method the call is attempted and +ArgumentError+ is still raised
otherwise.

If +try+ is called without arguments it yields the receiver to a given
block unless it is +nil+:

  @person.try do |p|
    ...
  end

Please also note that +try+ is defined on +Object+, therefore it won't work
with instances of classes that do not have +Object+ among their ancestors,
like direct subclasses of +BasicObject+. For example, using +try+ with
+SimpleDelegator+ will delegate +try+ to the target instead of calling it on
delegator itself.

Source | Google | Stack overflow

Edit

git clone [email protected]:sonic-pi-net/sonic-pi.git

cd sonic-pi

open app/server/ruby/vendor/activesupport/lib/active_support/core_ext/object/try.rb

Contribute

# Make a new branch

git checkout -b -your-name--update-docs-Object-try-for-pr


# Commit to git

git add app/server/ruby/vendor/activesupport/lib/active_support/core_ext/object/try.rbgit commit -m "better docs for Object#try"


# Open pull request

gem install hub # on a mac you can `brew install hub`

hub fork

git push <your name> -your-name--update-docs-Object-try-for-pr

hub pull-request


# Celebrate!