snippetrubyCritical
How to sum array of numbers in Ruby?
Viewed 0 times
numbersarrayhowsumruby
Problem
I have an array of integers.
For example:
Is there any nice way to get the sum of them?
I know, that
would work.
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.
Solution
Try this:
See Ruby's Enumerable Documentation
(note: the
array.inject(0){ |sum, x| sum + x }See Ruby's Enumerable Documentation
(note: the
0 base case is needed so that 0 will be returned on an empty array instead of nil)Code Snippets
array.inject(0){ |sum, x| sum + x }Context
Stack Overflow Q#1538789, score: 648
Revisions (0)
No revisions yet.