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

Rails’ index_by: the easy way to convert an Array to a Hash

As Aditya Sanghi notes in “Quickly convert an Array to a Hash”, a very quick way to convert an Array to a Hash, is to use Rails’ Enumerable#index_by:

Post.all.index_by { |post| post.id }
# => { 1 => #<Post ...>, 2 => #<Post ...>, ... }

Post.all.index_by(&:title)
# => { "My first post" => #<Post ...>, "My second post" => #<Post ...>, ... }

7 notes 0 comments

  1. rubyquicktips posted this

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