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.
ruby arrays math sum
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
90% accept rate
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
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
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
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(:+)
answered Oct 8 '09 at 16:28
jomey
191 31
Also works with 1.8.7 – glenn jackman Oct 8 '09 at 16:29
1Also works with Rails – khelll Oct 8 '09 at 18:30
beautiful, you made my day – marcgg Dec 23 '09 at 13:39
add comment声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did43537