Why is Enumerable#each_with_object deprecated?

Andrew Grimm picture Andrew Grimm · Mar 30, 2011 · Viewed 8.1k times · Source

According to APIdock, the Ruby method Enumerable#each_with_object is deprecated.

Unless it's mistaken (saying "deprecated on the latest stable version of Rails" makes me suspicious that maybe it's Rails' monkey-patching that's deprecated), why is it deprecated?

Answer

sawa picture sawa · Mar 30, 2011

This is rather an answer to a denial of the presupposition of your question, and is also to make sure what it is.


The each_with_object method saves you extra key-strokes. Suppose you are to create a hash out of an array. With inject, you need an extra h in:

array.inject({}){|h, a| do_something_to_h_using_a; h} # <= extra `h` here

but with each_with_object, you can save that typing:

array.each_with_object({}){|a, h| do_something_to_h_using_a} # <= no `h` here

So it is good to use it whenever possible, but there is a restriction. As I also answered in "How to group by count in array without using loop",

  • When the initial element is a mutable object such as an Array, Hash, String, you can use each_with_object.
  • When the initial element is an immutable object such as Numeric, you have to use inject:

    sum = (1..10).inject(0) {|sum, n| sum + n} # => 55