Rails 6 has added
This allows creating a hash from an enumerable with the value from a passed block or a default argument.
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
As you can see the code in
sanitized_terms gets verbose,
since we first initialize the hash,
mutate it, and then return its value.
This kind of task is not rare,
we need to perform it at various places.
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: