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 9 ’12

Quickly convert an Array to a Hash

As an example, let’s say you want to create an index of ActiveRecord objects by their id. Use the Hash constructor that accepts an Array of key-value pairs and do it in one line:

posts_by_id = Hash[*Post.all.map{ |p| [p.id, p] }.flatten]

This tip was submitted by http://Fullware.net/.

6 notes 0 comments

  1. sanemat reblogged this from rubyquicktips
  2. Fullware.net 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