Ruby 相当于 C# Linq Aggregate 方法

发布于 2024-10-18 06:11:35 字数 198 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我乃一代侩神 2024-10-25 06:11:35

这在数学以及几乎所有编程语言中通常被称为折叠。这是更一般的“变形论”概念的一个实例。 Ruby 继承了 Smalltalk 中此功能的名称,称为 inject:into: (使用方式类似于 aCollection insert: aStartValue into: aBlock。)因此,在 Ruby 中,它称为注入。它也有别名为 reduce,这有点不幸,因为这通常意味着稍微不同的东西。

您的 C# 示例在 Ruby 中看起来像这样:

factorial = [1, 2, 3, 4, 5].reduce(:*)

尽管其中之一可能更惯用:

factorial = (1..5).reduce(:*)
factorial = 1.upto(5).reduce(:*)

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(:*)
逆夏时光 2024-10-25 06:11:35

请参阅Enumerable#inject

用法:

a = [1,2,3,4,5]
factorial = a.inject(1) do |product, i|
  product * i
end

See Enumerable#inject.

Usage:

a = [1,2,3,4,5]
factorial = a.inject(1) do |product, i|
  product * i
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文