In Ruby 2.4+, you can calculate the sum of all numbers in an array using the Array#sum
method, for example, in the following way:
# Ruby 2.4+ print [1, 2, 3, 4, 5].sum #=> 15 print [1.2, -4, 4.5, 3, 10].sum #=> 14.7 print [].sum #=> 0
It will throw a TypeError
for non-numeric values (including numeric strings):
# Ruby 2.4+ # String can't be coerced into Integer (TypeError) print ['foo', 1, 2, 3].sum # String can't be coerced into Integer (TypeError) print ['1', '2', '3', '4', '5'].sum # nil can't be coerced into Integer (TypeError) print [1, 2, 3, nil].sum # ...
For versions of Ruby earlier than 2.4, you can use the Enumerable#inject
method (or its alias Enumerable#reduce
) instead, in the following way:
array.inject(0) { | sum, n | sum + n }
Passing 0
as the initial operand (or base case) is important as nil
would be returned for empty arrays otherwise.
You may shorten this using the following syntax:
array.inject(0, :+)
This follows the following method signature for Enumerable#inject
(where +
is passed as a symbol to the method):
# inject(initial, symbol) → obj
For example:
def sum(numbers) numbers.inject(0, :+) end print sum([1, 2, 3, 4, 5]) #=> 15 print sum([1.2, -4, 4.5, 3, 10]) #=> 14.7 print sum([]) #=> 0
It will throw a TypeError
for non-numeric values (including numeric strings):
# String can't be coerced into Integer (TypeError) print sum(['foo', 1, 2, 3]) # String can't be coerced into Integer (TypeError) print sum(['1', '2', '3', '4', '5']) # nil can't be coerced into Integer (TypeError) print sum([1, 2, 3, nil]) # ...
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.