问题
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