Ruby equivalent of C# Linq Aggregate method -
whats ruby equivalent of linq aggregate method. works this
var factorial = new[] { 1, 2, 3, 4, 5 }.aggregate((acc, i) => acc * i);
the variable acc getting accumulated every time value array sequence passed lambda..
this called fold in mathematics pretty programming language. it's instance of more general concept of catamorphism. ruby inherits name feature smalltalk, called inject:into:
(used acollection inject: astartvalue into: ablock.
) so, in ruby, called inject
. aliased reduce
, unfortunate, since means different.
your c# example in ruby:
factorial = [1, 2, 3, 4, 5].reduce(:*)
although 1 of these more idiomatic:
factorial = (1..5).reduce(:*) factorial = 1.upto(5).reduce(:*)
Comments
Post a Comment