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!
Aug 22 ’11

Directly access an object if it’s present

If you want to access an object only if it’s present, you can use Rails’ Object#presence.
The API docs on presence have a good explanation:

This is handy for any representation of objects where blank is the same as not present at all. For example, this simplifies a common check for HTTP POST/query parameters:

state   = params[:state]   if params[:state].present?
country = params[:country] if params[:country].present?
region  = state || country || 'US'

…becomes:

region = params[:state].presence || params[:country].presence || 'US'

12 notes 0 comments

  1. iluqman reblogged this from rubyquicktips and added:
    Tip that I submitted
  2. namxam reblogged this from rubyquicktips
  3. sanemat reblogged this from rubyquicktips
  4. Luqman Amjad submitted this to rubyquicktips

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