Today I Learned

hashrocket A Hashrocket project

Convert an enumerable to a hash

In Ruby if you want to easily convert your enumerable object into a hash, use index_by.

This uses the block result as the key and the element as the value.

Here is an example:

# In this example, `posts` is an array of Post objects
posts.index_by(&:slug)
=> { "slug-1" => <Post ...>, "slug-2" => <Post ...>, ...}
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.