Back
  1. 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_object will return the object you passed into it.

    We can save ourselves one line of code by using each_with_object over inject when building enumerable objects such as a hash. This is because each_with_object does not require the object we are building to be explicitly returned at the end of the provided block. This does not mean the inject method 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, inject is perfect.

    Example: Creating a hash of HTML status codes from an Array


  2. blog comments powered by Disqus