upvote
Ruby adds an alias `inject` for reduce. The #1 way I see it used there is like this:

  some_hash = my_array.inject({}) {|accumulator, item|  ... }
But I honestly very rarely use it (by either name) outside of a couple of pasted-in snippets (that I can't recall right now) where the strategy fits exceptionally well, probably because of the dumb reason that I tend to forget which block argument comes first (accumulator, or iterated item)! With other two-item argument lists such as `Hash#map` it being `key, value` makes sense, but with reduce/inject I don't see an obvious order. And I guess I learned before it was likely that some kind of AI autocomplete would be filling the args in for me.
reply
The name inject and the argument order comes from Smalltalk (Ruby is heavily inspired by it). In Smalltalk arguments are part of the message name:

collection inject: aValue into: aBlock

reply
Ruby inject appears to be derived from Smalltalk #inject:into:

#(1 2 3 4 5 6 7) inject: 10 into: [ :sum :each | sum + each squared ].

or from your example:

someHash := myArray inject: (Dictionary new) into: [ :accumulator :item | ... ].

The way I remember the order is it reflects the assignment you'd do is a while loop, sum := sum + each.

reply
It reduces n items to one item, recursively. The items don’t have to have the same type. Arguably accumulate is a more fitting name. I think of “reduce” as in cooking, boiling a volume of stuff down to some essence.

I also agree that a for loop is often clearer.

reply
I like the name `fold` as used by Haskell, Racket, et al. It gives me an image of folding up a long list into a ball, one chunk at a time.
reply
I like fold too, but I can never remember foldl vs foldr, it's always backwards to what I expect somehow
reply
> You could literally "reduce" and array of integers to a cancellation token, or a state object, or anything else

This is what reduce does, though? It reduces a list to a single thing. It seems like you're thinking of filter.

reply
There is a big difference in there I think.

'for' loop is mutating.

Using 'reduce', you can do the same functionally. In some (somewhat) purely functional languages, there is no choice.

reply
It doesn't have to be exactly correct. It just need to express intuitively the most common use(es?).

Aggregate, accumulate, combine for example.

reply