Rails 6 has added index_with to Enumerable. This allows creating a hash from an enumerable with the value from a passed block or a default argument.

#### Before

In one of our applications, we need to perform some params filtering, after which we pass it to ElasticSearch queries.

We receive unfiltered terms from Searchkit which are then filtered as below by sanitize_terms method.

As you can see the code in sanitized_terms gets verbose, since we first initialize the hash, mutate it, and then return its value.

#### Enumerable#index_with

This kind of task is not rare, we need to perform it at various places. For example:

Enter Enumerable#index_with. It provides us with a convenience method to perform this operation in a simplified form.

index_with creates a new hash object, using the key as the current element it is enumerating. Value is determined from the output of the passed block.

This helps us simplify our initial example in a much easier way:

index_with also allows to create a hash easily with default values: