Posted by: mikewilliamson on: April 22, 2011
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.