Just try!

I was reading the other day a post on “What’s new” with Rails and I came across a clever little method that is added to the Object class: Object#try. It works in a very simple way, it checks to see if an object responds to a method if it doesn’t well it fails misserably and does nothing but no errors are thrown. For those of you that love exceptions you are not going to like this.

I tried a very simple and probably is not the way that Rails implemented it but it does the job, a very small job since it doesn’t handle blocks or anything of the sort. Keep in mind that I came up with this in 0.005 seconds so it’s probably wrong in some very serious ways.

class Object
  def try method
   if respond_to? method
      send method
   else
     self
   end
  end
end

"hello".try(:hello) #=> "hello"
"hello".hello #=> NoMethodError
"1".try(:hello).try(:to_i) #=> 1

I’m sure Rails version is more complete than mine. I would expect it to handle arguments and blocks. If it doesn’t then what are they thinking!

And as Ben Parker once said, with great power comes great responsibility. I do see some places where this is going to cause more pain than relief