ruby inject sum

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
發佈了13 篇原創文章 · 獲贊 0 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章