Rails ActiveSupport Enumerable adds index_with method. This method allows creating hash with a value from block passed or default value. This is useful when we want to create a hash and value needs to be generated with some custom logic.
- Rails Enumerable already has index_by which can be used to index elements of enumerable with a particular key.
- Enumerable#index_with comes in handy when we want a hash with customizable value.
Let’s say we have a Post model as given below.
We have a post object as given below.
Enumerable#index_with with a block
Now, we can use
Enumerable#index_with as given below.
Enumerable#index_with with a deafult argument
index_with used whatever passed to it as an argument as a value
for each key if block is not used.
Check out all the available methods on Enumerable to know more about handling Enumerable objects. If you want to try this feature out, compile with Rails master from Github.