---
title: "Rails 6 adds Enumerable#index_with"
description: "Rails 6 adds Enumerable#index_with"
canonical_url: "https://www.bigbinary.com/blog/rails-6-adds-enumerable-index_with"
markdown_url: "https://www.bigbinary.com/blog/rails-6-adds-enumerable-index_with.md"
---

# Rails 6 adds Enumerable#index_with

Rails 6 adds Enumerable#index_with

- Author: Amit Choudhary
- Published: June 17, 2019
- Categories: Rails 6, Rails

Rails 6 added [index_with](https://github.com/rails/rails/pull/32523) on
[Enumerable](https://api.rubyonrails.org/v5.2/classes/Enumerable.html) 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](https://ruby-doc.org/core-2.5.1/Array.html#method-i-map) along with
[to_h](https://ruby-doc.org/core-2.5.1/Array.html#method-i-to_h).

[index_with](https://github.com/rails/rails/pull/32523) 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](https://ruby-doc.org/core-2.5.1/Array.html#method-i-map) and
[to_h](https://ruby-doc.org/core-2.5.1/Array.html#method-i-to_h).

```ruby

> > 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](https://github.com/rails/rails/pull/32523) in Rails 6.

```ruby

> > 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](https://github.com/rails/rails/pull/32523).

## Links

- [Human page](https://www.bigbinary.com/blog/rails-6-adds-enumerable-index_with)
