Wednesday, July 7, 2010

Ruby's Object#try method

Yesterday I blogged about implicitly testing for nil, relying on Ruby's definition of truth, rather than the explicit Object#nil? to keep code terse.

Here's another example of keeping code terse when handling nil values with Object#try. This is particularly helpful when working with ERB:

# in ERB template if order.user
The simplified version:
# in ERB template

Something I didn't know previously to writing this post, is Object#trysupports arguments similar to Object#send.

Object#try was added to ActiveSupport in Rails 2.3.2.

Please note this blog is no longer maintained. Please visit CivilCode Inc - Custom Software Development.