Rails 6 adds Enumerable#index_with

Amit Choudhary

By Amit Choudhary

on 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.

1
2> > address = Address.first
3> > SELECT "addresses".\* FROM "addresses"
4> > ORDER BY "addresses"."id" ASC LIMIT \$1 [["LIMIT", 1]]
5
6=> #<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">
7
8> > NAME_ATTRIBUTES = [:first_name, :last_name]
9
10=> [:first_name, :last_name]
11
12> > NAME_ATTRIBUTES.map { |attr| [attr, address.public_send(attr)] }.to_h
13
14=> {: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.

1
2> > address = Address.first
3> > SELECT "addresses".\* FROM "addresses"
4> > ORDER BY "addresses"."id" ASC LIMIT \$1 [["LIMIT", 1]]
5
6=> #<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">
7
8> > NAME_ATTRIBUTES = [:first_name, :last_name]
9
10=> [:first_name, :last_name]
11
12> > NAME_ATTRIBUTES.index_with { |attr| address.public_send(attr) }
13
14=> {:first_name=>"Amit", :last_name=>"Choudhary"}
15
16> > NAME_ATTRIBUTES.index_with('Default')
17
18=> {:first_name=>"Default", :last_name=>"Default"}

Here is the relevant pull request.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.