Switching the receiver and the argument of `Enumerable#inject`

风格不统一 提交于 2019-12-08 09:03:35

问题


When Enumerable#inject is used, most of the times, we want the result to be the same class (and often the same object) as the initial object that appears as the argument of inject. For example, we use it like:

[1, 2, 3, 4, 5]
.inject(5){|i, e| i += e}
# => 20

[3, 4, 5]
.inject(1 => 1, 2 => 1){|h, e| h[e] = h[e - 1] + h[e - 2]; h}
# => {1=>1, 2=>1, 3=>2, 4=>3, 5=>5}

From the point of view that this operation takes the initial value and modifies it into the final output, it would be more natural to have the initial value as the receiver and write like this:

5
.foo([1, 2, 3, 4, 5]){|i, e| i += e}
# => 20

{1 => 1, 2 => 1}
.foo([3, 4, 5]){|h, e| h[e] = h[e - 1] + h[e - 2]; h}
# => {1=>1, 2=>1, 3=>2, 4=>3, 5=>5}

where Object#foo would be defined as

def foo enum, ≺ enum.inject(self, &pr) end

Is there a ready-made method in some library that resembles this foo?

来源:https://stackoverflow.com/questions/16123680/switching-the-receiver-and-the-argument-of-enumerableinject

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