-
Ruby Protip: Build objects using each_with_object
January 20, 2011 by kfaustino comments
In Ruby 1.9, a class that includes Enumerable will inherit a method called
each_with_object. This method allows you to iterate a given block for each element with an object you specify. Once the iteration is complete,each_with_objectwill return the object you passed into it.We can save ourselves one line of code by using
each_with_objectoverinjectwhen building enumerable objects such as a hash. This is becauseeach_with_objectdoes not require the object we are building to be explicitly returned at the end of the provided block. This does not mean theinjectmethod shouldn’t be used. When you need to perform calculations on a collection of items and would like to return the result, such as a sum,injectis perfect.Example: Creating a hash of HTML status codes from an Array
- blog comments powered by Disqus
