Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Enumerable#each_with_object deprecated?

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?

like image 384
Andrew Grimm Avatar asked Mar 30 '11 01:03

Andrew Grimm


People also ask

What does it mean by enumerable?

To declare something to as an enumerable is to declare that it corresponds to a specific number, allowing it to be given a place in a Dictionary that represents countable components of an object.

What is the use of enumerable?

The term “Enumerable” defines an object that is meant to be iterated over, passing over each element once in order.

Why is IEnumerable used?

IEnumerable interface is used when we want to iterate among our classes using a foreach loop. The IEnumerable interface has one method, GetEnumerator, that returns an IEnumerator interface that helps us to iterate among the class using the foreach loop.

What is meant by enumerable in programming?

Enumerable properties are those properties whose internal enumerable flag is set to true, which is the default for properties created via simple assignment or via a property initializer. Properties defined via Object. defineProperty and such are not enumerable by default.


2 Answers

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
    
like image 120
sawa Avatar answered Sep 28 '22 16:09

sawa


There's no note in the Ruby trunk source code, the method is still there (contrary to that page's claims), and there's been no talk of it on the mailing list that I can find.

APIdock is simply confused. The point where APIdock says it was deprecated is actually the earliest version with the method in the standard library (rather than just being an ActiveSupport backport extension), and Rails disables its version if you're using a Ruby that has the method, so APIdock appears to be confused by the method migrating between projects.

like image 20
Chuck Avatar answered Sep 28 '22 16:09

Chuck