如何计算 Ruby 数组中所有值的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21839832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:24:00  来源:igfitidea点击:

How to calculate the Sum of all Values in a Ruby Array

rubyarrayssum

提问by newUserNameHere

I have an array as follows:

我有一个数组如下:

a = [1,2,5,8]

a = [1,2,5,8]

I want to calculate the value of all the elements added(or multiplied) together.

我想计算所有元素相加(或相乘)在一起的值。

回答by newUserNameHere

a.inject{ |sum,x| sum + x }

Or slightly shorter and faster:

或者稍微短一点和更快:

a.inject(:+)

For multiplication or whatever else, just change the sign: a.inject(:*)

对于乘法或其他任何事情,只需更改符号: a.inject(:*)