I recently needed to create a hash lookup from an object using the ID as the lookup key and the full object as the value in our rails app. It wasn’t a difficult concept and there were several ways this could be accomplished; however, we just couldn’t find a way that made sense or didn’t involve looping. That is, until we found
Let’s assume we have an
Animal class and an
Animals list class:
So we’d have a list of animals:
Our first solution took advantage of
This was our default approach in conversion in the past, but creating an array of arrays just to use this approach seemed lengthy and unnecessary.
Using Enumerable .reduce()
Our second solution took advantage of the reduce method in the Enumerable Class:
This is slightly better, since we don’t have to map on the array only to convert; but needing to return the hash at the end isn’t ideal either. Both solutions so far would usually require a doc lookup for .reduce and Hash[a].
Using Enumerable .index_by()
Our final solution, we used the Enumerable
.index_by accepts a block. So if you want to index by two fields such as first and last name, you could easily do this with the block:
All three solutions yield the same result; a hash with the keys being the ID of the object: