Rails 6 adds Enumerable#index_with

Amit Choudhary

Amit Choudhary

June 17, 2019

This blog is part of our  Rails 6 series.

Rails 6 added index_with on Enumerable module. This will help in creating a hash from an enumerator with default or fetched values.

Before Rails 6, we can achieve this by calling map along with to_h.

index_with takes both value or a block as a parameter.

Let's checkout how it works.

Rails 5.2

Let's create a hash from an array in Rails 5.2 using map and to_h.


> > address = Address.first
> > SELECT "addresses".\* FROM "addresses"
> > ORDER BY "addresses"."id" ASC LIMIT \$1 [["LIMIT", 1]]

=> #<Address id: 1, first_name: "Amit", last_name: "Choudhary", state: "California", created_at: "2019-03-21 10:03:57", updated_at: "2019-03-21 10:03:57">

> > NAME_ATTRIBUTES = [:first_name, :last_name]

=> [:first_name, :last_name]

> > NAME_ATTRIBUTES.map { |attr| [attr, address.public_send(attr)] }.to_h

=> {:first_name=>"Amit", :last_name=>"Choudhary"}

Rails 6.0.0.beta2

Now let's create the same hash from the array using index_with in Rails 6.


> > address = Address.first
> > SELECT "addresses".\* FROM "addresses"
> > ORDER BY "addresses"."id" ASC LIMIT \$1 [["LIMIT", 1]]

=> #<Address id: 1, first_name: "Amit", last_name: "Choudhary", state: "California", created_at: "2019-03-21 10:02:47", updated_at: "2019-03-21 10:02:47">

> > NAME_ATTRIBUTES = [:first_name, :last_name]

=> [:first_name, :last_name]

> > NAME_ATTRIBUTES.index_with { |attr| address.public_send(attr) }

=> {:first_name=>"Amit", :last_name=>"Choudhary"}

> > NAME_ATTRIBUTES.index_with('Default')

=> {:first_name=>"Default", :last_name=>"Default"}

Here is the relevant pull request.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.