part of the family
beyond corporate purpose

Rails `try`

03 Jun 2009

try is one of those small new additions in the Rails 2.3 release. Luckily I found out about it via a Railscast

What is it?

From the documentation:

Invokes the method identified by the symbol method, passing it any arguments and/or the block specified, just like the regular Ruby Object#send does. Unlike that method however, a NoMethodError exception will not be raised and nil will be returned instead, if the receiving object is a nil object or NilClass.


What did you just say?

The code above normally throws an exception if someobject is nil. By using try it just returns nil.

Don’t overuse this.

blog comments powered by Disqus