Reputation: 10014
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
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