.try


I’ve been doing a lot of reading lately, most of that in regards to user authentication for the API I’m working on. I usually end up seeing new things that I mess around with to see how they work. One of those is the try method provided by rails.

So, I thought this method was really cool. Unfortunately I don’t remember exactly where I came across it. It was my first time encountering it. Apidock has a pretty good example and explanation here. So basically, it returns nil if the object doesn’t respond to the passed method, rather than NoMethodError.

2.1.5 :006 > @user.try(:name)
 => "Trevor" 
2.1.5 :007 > @user.try(:foo)
 => nil 
2.1.5 :008 > @user.foo
NoMethodError: undefined method `foo' for #<User:0x007ff05c5828f8>
...

I suppose the only possible drawback would be readability. I could see something like:

@product.name unless @product.name.nil?

Reading better than:

@product.try(:name)

Just kind of bumped into this method, but thought it seemed like it could be pretty handy.

comments powered by Disqus