簡體   English   中英

如何在Ruby中找到每個數組的總和

[英]How to find each sum of array in Ruby

我試圖找到每個數組的總和。

(1..9).to_a.combination(3).to_a.each{ |item| item.inject{:+}}

但我的代碼給出了以下內容。

[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 2, 6], [1, 2, 7], [1, 2, 8], [1, 2, 9], 
[1, 3, 4], [1, 3, 5], [1, 3, 6], [1, 3, 7], [1, 3, 8], ...

我期待的是這樣的事情。

[6, 7, 8, 9,...]

如何找到每個數組的總和?

您非常接近,對您的代碼進行一些更改可能會有所幫助:

(1..9).to_a.combination(3).map { |a| a.inject(:+) }
(1..9).to_a.combination(3).to_a.map { |item| item.inject(:+) }

我用#reduce找到了另一種方法。

(1..9).to_a.combination(3).map { |item| item.reduce(:+) }

暫無
暫無

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

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