好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

ruby inject sum

ruby inject sum

How to sum array members in Ruby?

up vote 1 down vote favorite

1

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

edited Oct 8 '09 at 21:21

Mike Woodhouse
12.1k   1   14   35

asked Oct 8 '09 at 16:04

brainfck
721   1 10


 

     

add comment  

start a bounty

offer  of my own reputation for an answer to this question

     What is bounty?

4 Answers

active newest votes

up vote 12 down vote accepted

Try this:

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

Documentation

link | flag

answered Oct 8 '09 at 16:07

zenazn
2,835 9 15

 

 

 

jorney's array.inject(:+) is more efficient. –  Peter Oct 9 '09 at 7:09

 

add comment

up vote 4 down vote

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

answered Oct 8 '09 at 18:29

jrhicks
1,528 2 15

 

 

 

I've done this before, very useful :-) –  Topher Fangio Oct 8 '09 at 18:30

 

add comment

up vote 4 down vote

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

  require     'activesupport'  
array . sum

link | flag

answered Oct 8 '09 at 16:49

Mike Woodhouse
12.1k 1 14 35

 

     

add comment

up vote 19 down vote

Or try the ruby 1.9 way

array.inject(:+)

link | flag

answered Oct 8 '09 at 16:28

jomey
191 3

 

1

 

Also works with 1.8.7 –  glenn jackman Oct 8 '09 at 16:29

1  

Also works with Rails –  khelll Oct 8 '09 at 18:30

   

beautiful, you made my day –  marcgg Dec 23 '09 at 13:39

 

add comment

查看更多关于ruby inject sum的详细内容...

  阅读:30次