spike
spike

Reputation: 10014

Why are the arguments of reduce in the order they are?

I always forget the arguments of reduce in ruby (https://ruby-doc.org/core/Enumerable.html#method-i-reduce) which is called like this:

(5..10).reduce { |sum, n| sum + n }

Is there a language design reason why the accumulator is passed in first or is it just an arbitrary choice? JS works the same way.

Upvotes: 2

Views: 120

Answers (1)

tadman
tadman

Reputation: 211740

It's mostly so you can do things like this:

(5..10).reduce(&:+)

Where that expands to:

(5..10).reduce { |a,b| a.send(:+, b) } 

Which is equivalent to:

(5..10).reduce { |a,b| a + b }

So it makes sense that way. Note the order is the opposite of each_with_object.

Upvotes: 1

Related Questions