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!
Apr 14 ’11

Using “try” with a hash to check existence of a key

The try method is awesome. Check the documentation.
It is usually used to call a method on an object if it exists, or return nil if it doesn’t.

But sometimes, it is not used with hashes, but this also works perfectly:

params[:search] ? params[:search][:name] : nil

# Can also be written as...
params[:search].try(:[],:name)

Clean!

This tip was submitted by Miguel Camba.

31 notes 0 comments

  1. deepcleaningcorona reblogged this from rubyquicktips
  2. spring-mt reblogged this from rubyquicktips
  3. nopolitica reblogged this from rubyquicktips
  4. Miguel Camba 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