How do you iterate over two collections, and at the same time generate a new, third collection based on elements selected from the previous two? In other words, how do I create a list of paired things by ticking down two others?
The things that I’ve been wondering about and now love:
- Enumerator (new love)
- Enumerable (rediscovered love)
- Inject (constantly blows my mind)
I first came across this problem during the decoder exercise early on at the Flatiron School. I had an encoded message and a cypher, and I wanted to make a new hash by iterating over both and setting the cypher as a key and the code as its value. There are tons of workarounds but I got a bit fixated on doing it more or less in one go.
More recently I’ve been perplexed by the Enumerator class. One super cool thing it lets you do is keep track of internal position. What this means is that after you set it up, you can do:
All that’s needed to unlock this capability is to call the collection with an enumerable method, sans block. And the only requirement is that the method includes an implementation of each, which as far as I know is every method in Enumerable. So:
Once you’ve made an Enumerator object, you can access this amazing ‘internal tracker’.
Side note, Ruby also has the nifty to_enum method that turns anything into an object of the Enumerator class. So (1..4).each is equivalent to (1..4).to_enum, though they are different instances of the Enumerator class.
Next, lets add some inject to the mix.
Inject is mindblowing and has tons of uses and applications, but it basically works by taking a collection and doing something to each element in context of the previous element. A basic example is summing numbers:
Here inject is grabbing the first item in the array, adding the second item to it, and then using that as the new total, before continuing to add subsequent items in the same way. Interestingly, inject also lets you pass an argument before the block to use as the starting value.
And because you can easily pass things into arrays and hashes, you can also slip in an empty one as your starter. Don’t forget to specify that you want the new collection returned.
Lastly, by combining Enumerator and inject you can make one neat, succinct, clear, and logical iterator that’s (sort of) running 2 parallel iterations.
After writing this I became fascinated with making a method that could take 2 collections of arrays, hashes, or ranges, and a last argument for the rate of iterating over each collection relative to the other. In the works, stay tuned.
Make yourself useful.