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 ...

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 ...

Nice and clean.

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