Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 lambda..

like image 221
RameshVel Avatar asked Feb 18 '11 01:02

RameshVel


2 Answers

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(:*)
like image 91
Jörg W Mittag Avatar answered Oct 25 '22 21:10

Jörg W Mittag


See Enumerable#inject.

Usage:

a = [1,2,3,4,5]
factorial = a.inject(1) do |product, i|
  product * i
end
like image 29
Platinum Azure Avatar answered Oct 25 '22 21:10

Platinum Azure