SHARE:
Uncategorized

Ruby’s #each_with_object

Flatiron School / 6 November 2012

The following is a guest post by Kevin Curtin and originally appeared on his blog. Kevin is currently a student a The Flatiron School. You can learn more about him here, or follow him on twitter here.

Ruby’s #inject method is pretty popular. We often use it so that we don’t have to initialize local variables prior to executing a block. Check out the refactored code below using the inject method for an example:

While inject can be great for cleaning up blocks of code, I don’t like that you have to explicity return the hash on the last line of the block so that it can be passed to the next iteration. If, for example, I removed hash on line 10 I would get an error that looks like this:

That’s no good. Luckily for us we have #each_with_object

As you can see, #each_with_object behaves like inject with two key differences:

  1. The arguments you are sending to the block are reversed
  2. You don’t need to explicity return the value to be passed on on the last line

Enjoy!

A Message from Our Dean to Our Students Previous Post Submitting a Pull Request Next Post