Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Feb 10 ’10

Give it a try!

As of Rails 2.3, there is a handy new try method on objects, which allows you to invoke a method on a possibly nil object without throwing a NoMethodError. This saves you the trouble of checking if your object is nil before accessing a method.

For example, previously you’d need to do something like this:

article = Article.find_by_title("My Article")
unless article.nil? 
  article.body
end

With try you can skip the nil? check and do the following:

Article.find_by_title("My Article").try(:body) => #body or nil

Check out the documentation on try.

This post was ‘manually’ reblogged from michaelbulat.

15 notes 0 comments

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus