Zip: The Unsung Hero of Ruby Enumerables

There are a lot of Ruby enumerables that are headliners. “Each”, “Reduce”, “Map”, “Sort_by”. They are beloved by all and used pretty frequently.

There is one enumerable who has saved me quite a few times though, and who does not get the credit it deserves. That enumerable would be my good friend, “Zip.”

For those unfamiliar with .zip, here is a basic introduction:

.zip can be used to combine collections a corresponding order. As an example, calling it on two collections, one as the message receiver and one as the message’s argument:

.zip will also work with multiple arrays. To demonstrate, we can assemble information about the 3 players involved with the 2016 Villanova NCAA Championship winning final play:

While that is pretty nice, that is not .zip’s niftiest trick. You can use .zip to create hashes on the fly as well.

So whenever you find yourself needing to compare array values, ordering 4 arrays, or banging your head against the keyboard because “.to_h” isn’t working, remember .zip will always have your back.

Show your support

Clapping shows how much you appreciated Jason Hanna’s story.