簡體   English   中英

Ruby相當於C#Linq Aggregate方法

[英]Ruby equivalent of C# Linq Aggregate method

什么是相當於Linq Aggregate方法的紅寶石。 它的工作原理是這樣的

  var factorial = new[] { 1, 2, 3, 4, 5 }.Aggregate((acc, i) => acc * i);

每次將數組序列中的值傳遞給lambda時,變量acc都會累積。

這通常被稱為數學折疊以及幾乎任何編程語言。 它是一個更為籠統的概念的一個實例 Ruby從Smalltalk繼承了這個特性的名稱,在那里它被稱為inject:into:aCollection inject: aStartValue into: aBlock.一樣使用aCollection inject: aStartValue into: aBlock. )因此,在Ruby中,它被稱為inject 它也有別名reduce ,這有點不幸,因為這通常意味着略有不同。

您的C#示例在Ruby中看起來像這樣:

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

雖然其中一個可能更慣用:

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

請參閱Enumerable#inject

用法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM