开发者

Ruby equivalent of C# Linq Aggregate method

开发者 https://www.devze.com 2023-02-11 00:36 出处:网络
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);

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
0

精彩评论

暂无评论...
验证码 换一张
取 消