Do or do not. There is no try. Wait, yes there is.

Cruising through Stackoverflow I noticed some syntax that I had never seen before:

@blog.user.try(:username)

Interested, I looked it up. As far as I can tell, it seems that one of the clever folks behind Github posted it as a helpful snippet on his blog.
From there it seems to have made its way into the Rails ActiveSupport library and then into Ruby 1.9 itself. Basically its the same as send except it swallows errors and just returns nil.
An example from the docs:

@person ? @person.name : nil

could be replaced with:

@person.try(:name)

Coolness! I know this will be making its way into my own code shortly. Check out Scott Harvey’s excellent explanation of the try method and also take a look at the documentation here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s