Ruby 相当于 C# Linq Aggregate 方法
Linq Aggregate 方法的 ruby 等效项是什么?它的工作原理是这样的,
var factorial = new[] { 1, 2, 3, 4, 5 }.Aggregate((acc, i) => acc * i);
每次将数组序列中的值传递给 lambda 时,变量 acc 就会累积。
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..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这在数学以及几乎所有编程语言中通常被称为折叠。这是更一般的“变形论”概念的一个实例。 Ruby 继承了 Smalltalk 中此功能的名称,称为
inject:into:
(使用方式类似于aCollection insert: aStartValue into: aBlock。
)因此,在 Ruby 中,它称为注入
。它也有别名为reduce
,这有点不幸,因为这通常意味着稍微不同的东西。您的 C# 示例在 Ruby 中看起来像这样:
尽管其中之一可能更惯用:
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 likeaCollection inject: aStartValue into: aBlock.
) So, in Ruby, it is calledinject
. It is also aliased toreduce
, which is somewhat unfortunate, since that usually means something slightly different.Your C# example would look something like this in Ruby:
Although one of these would probably be more idiomatic:
请参阅Enumerable#inject。
用法:
See Enumerable#inject.
Usage: