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 lambda..
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With