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!
May 19 ’10

Select from a Hash by value

Say, we have a Hash with codes for colors:

COLOR = { :red => 1, :white => 2, :black => 3, :yellow => 4 }

…and we want to check which color belongs to number 3.

COLOR.invert[3]
#=> :black

This tip uses Hash#invert, which “returns a new hash, created by using hsh‘s values as keys, and the keys as values.”

20 notes 0 comments

  1. atm09td reblogged this from rubyquicktips
  2. reddavis reblogged this from rubyquicktips
  3. rubyloveinfo reblogged this from rubyquicktips
  4. morii 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