Today I discovered Ruby’s
each_with_object method and I thought it was pretty nifty. Here is how it works.
An example with an output array of doubled values:
You may say, “meh, this works one heck of a lot like
map but clunkier.” And you’d be right.
But if you want to output a hash, you may start to see its value. Here we’ll output a hash that counts instances of a letter in an array:
Now that’s pretty nifty.
The other option is to use plain
each, hoist the output variable in advance, and then return it. Like this:
If you’d like a few more examples, check out this post by Agnieszka Matysek of womanonrails.com.