How to Find the Sum of an Array of Numeric Strings in Ruby?

In Ruby, you can get the sum of all numbers in an array by using Array#sum or the Enumerable#inject method:

# Ruby 2.4+
print [1, 2, 3, 4, 5].sum #=> 15
# Ruby <2.4
print [1, 2, 3, 4, 5].inject(0, :+) #=> 15

However, neither of these work on an array of numeric strings:

# Ruby 2.4+
# String can't be coerced into Integer (TypeError)
print ['1', '2', '3', '4', '5'].sum
# Ruby <2.4
# String can't be coerced into Integer (TypeError)
print ['1', '2', '3', '4', '5'].inject(0, :+)

Therefore, to calculate the sum of an array of numeric strings, you can do either of the following:

# Ruby 2.4+
print ['1', '2', '3', '4', '5'].map(&:to_f).sum #=> 15.0
# Ruby <2.4+
print ['1', '2', '3', '4', '5'].map(&:to_f).inject(0, :+) #=> 15.0

In both the above-mentioned instances, the Array#map method is used to convert numbers to float first, and then sum of all elements of the array is calculated using either Array#sum or Enumerable#inject method. This works with numeric strings, integers, rational numbers, etc. (as you can see in the examples below):

# Ruby 2.4+
def sum(numbers)
    numbers.map(&:to_f).sum
end

print sum(['1', '2', '3', '4', '5']) #=> 15.0
print sum([1, '2', 3, '4', 5]) #=> 15.0
print sum([1, 2, 3, 4, 5]) #=> 15.0

print sum(['1.2', '-4', '4.5', '3', '10']) #=> 14.7
print sum(['1', '-2', '3', '-4', '5']) #=> 3.0

print sum(['']) #=> 0.0
print sum([]) #=> 0
# Ruby <2.4+
def sum(numbers)
    numbers.map(&:to_f).inject(0, :+)
end

print sum(['1', '2', '3', '4', '5']) #=> 15.0
print sum([1, '2', 3, '4', 5]) #=> 15.0
print sum([1, 2, 3, 4, 5]) #=> 15.0

print sum(['1.2', '-4', '4.5', '3', '10']) #=> 14.7
print sum(['1', '-2', '3', '-4', '5']) #=> 3.0

print sum(['']) #=> 0.0
print sum([]) #=> 0

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.