Call Montréal, Canada 524-949-6869

Blog

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
@order.user.name if order.user
The simplified version:
# in ERB template
@order.user.try(:name)

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.

Monday, July 5, 2010

Keeping your code terse, testing for "nil"

On a recent project, I was seeing many occurrences of this statement:

if !order.user.nil?
  # do something ...
end

While this is correct, it's not idiomatic Ruby. Ruby is a terse language. Let's keep our code terse as well. Consider how Ruby defines truth:

"Ruby has a simple definition of truth. Any value that is not nil or the constant false is true." (Agile Development with Rails, 3rd Edition, pg 319).

This means testing for "nil" is redundant. We can therefore shorten our code to:

if order.user
  # do something ...
end

Nice and clean.

Developing Ruby on Rails applications and custom Content Management Systems in Montréal. Contact Firsthand.