gpt4 book ai didi

ruby - 为什么不推荐使用 Enumerable#each_with_object?

转载 作者:数据小太阳 更新时间:2023-10-29 06:39:47 24 4
gpt4 key购买 nike

根据 APIdock ,Ruby 方法 Enumerable#each_with_object 已弃用。

除非它是错误的(说“在最新稳定版本的 Rails 上弃用”让我怀疑可能是 Rails 的猴子补丁被弃用了),为什么它被弃用了?

最佳答案

这更像是对否定你问题的预设的回答,也是为了确定它是什么。


each_with_object 方法可以节省您额外的击键次数。假设您要从数组中创建散列。使用inject,你需要一个额外的h in:

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

但使用 each_with_object,您可以节省输入:

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

所以尽可能使用它是好的,但是有一个限制。正如我在“How to group by count in array without using loop”中的回答,

  • 当初始元素是可变对象时,例如ArrayHashString,您可以使用 each_with_object
  • 当初始元素是不可变对象时,例如Numeric,您必须使用inject:

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

关于ruby - 为什么不推荐使用 Enumerable#each_with_object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5481009/

24 4 0