Why is Enumerable#each_with_object deprecated?

风流意气都作罢 提交于 2019-11-27 05:46:12

问题


According 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?


回答1:


Well, that seems a bit weird. Even Agile Rails writes somewhere : "The Ruby 1.9 each_with_object method was found to be so handy that the Rails crew backported it to Ruby 1.8 for you". Seems like an error in apidock ? I don't see any reason why it would be :/




回答2:


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


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

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 here,

  • 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 as below.

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




回答3:


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.



来源:https://stackoverflow.com/questions/5481009/why-is-enumerableeach-with-object-deprecated

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!