Ruby equivalent of C# Linq Aggregate method
Whats the ruby equivalent of Linq Aggregate method. It works something like this
var factorial = new[] { 1, 2, 3, 4, 5 }.Aggregate((acc, i) => acc * i);
the variable acc is getting accumulated every time the value from the array sequence is passed to the lam开发者_如何学Pythonbda..
This is usually called a fold in mathematics as well as pretty much any programming language. It's an instance of the more general concept of a catamorphism. Ruby inherits its name for this feature from Smalltalk, where it is called inject:into:
(used like aCollection inject: aStartValue into: aBlock.
) So, in Ruby, it is called inject
. It is also aliased to reduce
, which is somewhat unfortunate, since that usually means something slightly different.
Your C# example would look something like this in Ruby:
factorial = [1, 2, 3, 4, 5].reduce(:*)
Although one of these would probably be more idiomatic:
factorial = (1..5).reduce(:*)
factorial = 1.upto(5).reduce(:*)
See Enumerable#inject.
Usage:
a = [1,2,3,4,5]
factorial = a.inject(1) do |product, i|
product * i
end
精彩评论