back

When to use Object#try

I’ve been going back and forth about whether to use try. If you don’t know, Object#try does this:

1
2
3
  
dog.try(:woof!)

If dog is not nil, the dog will get woof! sent to it, otherwise, it will return nil and not raise an undefined method error. Try lets you call a method on an possibly nil object. The second argument is the arguments to the method.

The problem is that having places in your code where something may or may not be nil can lead to a tangled mess. If your codebase assumes that something is not nil, then you wouldn’t want to use try just to deal with bad data.

However, recently I’ve been using try like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Person < AR::Base

  has_one :dog

  def walk_dog_without_try
    dog ? dog.walk : walk_alone
  end

  def walk_dog_with_try
    dog.try(:walk) || walk_alone
  end

end

Since the initial version without try already assumes that dog might be nil, it seems appropriate to get rid of the ternary operator and instead just use try combined with ||.

This may be slower, and less clear, I’m not sure.

September 25, 2009