如何总结在Ruby中的数字阵列? [英] How to sum array of numbers in Ruby?
本文介绍了如何总结在Ruby中的数字阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个整数数组。
例如:
array = [123,321,12389]
有没有什么好的办法让他们的总和?
Is there any nice way to get the sum of them?
我知道,
sum = 0
array.each { |a| sum+=a }
会工作。
推荐答案
试试这个:
array.inject(0){|sum,x| sum + x }
(注:需要在 0
基本情况,使 0
将返回一个空数组返回,而不是无
)
(note: the 0
base case is needed so that 0
will be returned on an empty array instead of nil
)
这篇关于如何总结在Ruby中的数字阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文