views:

1953

answers:

4

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.

+12  A: 

Try this:

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

Documentation

zenazn
jorney's `array.inject(:+)` is more efficient.
Peter
+19  A: 

Or try the ruby 1.9 way

array.inject(:+)

jomey
Also works with 1.8.7
glenn jackman
Also works with Rails
khelll
beautiful, you made my day
marcgg
+4  A: 

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

require 'activesupport'
array.sum
Mike Woodhouse
+4  A: 

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
jrhicks
I've done this before, very useful :-)
Topher Fangio