Rails each_with_object vs inject
Short & Sweet:
Each_with_object is the same thing as inject, except you don’t have to return the object at the end of the block you pass. Since most of the time you are using inject, you have to return the hash or array as the last line in the block, using each with object will let you do the same thing, but with less code.
Just noticed D2H tweet about each_with_object, and realized I hadn’t heard about it. It’s basically an easier way to do what you are already doing with inject, and it should be a bit easier to understand for people new to Ruby, as inject seems to be confusing for a lot of people. (Jay fields on inject)
So, it started at this thread on inject at lighthouse where Adam Keys proposed adding “injecting” as an enumerable method. Koz suggested that they instead backport each_with_object from Ruby 1.9, which Adam then did.
So, I will shutup and show what it does now:
January 03, 2009
