ruby inject sum

本文介绍了几种在Ruby中计算数组元素总和的方法,包括使用inject方法、定义自定义sum方法及利用Rails框架提供的便利方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have an array of integers.

For example:

array = [123,321,12389]

Is there any nice way to get the sum of them?

I know, that

sum = 0
array
.each { |a| sum+=a }

would work.

link | flag

 
 
  
add comment
 
start a bounty

offer  of my own reputation for an answer to this question

     What is bounty?
<script></script>

4 Answers

up vote 12 down vote accepted

Try this:

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

Documentation

link | flag
 
 
 
up vote
 
flag
jorney's array.inject(:+) is more efficient. –  Peter Oct 9 '09 at 7:09
add comment

Add sum to the Array class

class Array
   
def sum
       
self.inject{|sum,x| sum + x }
   
end
end

Then do fun stuff like:

[1,2,3,4].sum
link | flag
 
 
 
up vote
 
flag
I've done this before, very useful :-) –  Topher Fangio Oct 8 '09 at 18:30
add comment

Alternatively (just for comparison), if you have Rails installed (actually just ActiveSupport):

require 'activesupport'
array
.sum
link | flag
 
 
  
add comment

Or try the ruby 1.9 way

array.inject(:+)

link | flag
 
 
1
up vote
 
flag
Also works with 1.8.7 –  glenn jackman Oct 8 '09 at 16:29
1
up vote
 
flag
Also works with Rails –  khelll Oct 8 '09 at 18:30
 
up vote
 
flag
beautiful, you made my day –  marcgg Dec 23 '09 at 13:39
add comment
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值