Steve_D
Steve_D

Reputation: 553

How to get the sum an array of strings in ruby

I have an array of decimal numbers as strings, I need to get the sum of the array, I have tried iterating over the array and changing each number to a float but that just returns a whole number each time and I need the sum to be a decimal. What data type should I change the string to, and the best way to get the sum of the array would be helpful.

Upvotes: 6

Views: 8553

Answers (4)

Frank
Frank

Reputation: 71

  • First we put string of numbers into Array of strings
  • Second we change the whole block into numbers
  • Then we sum it all up, if Array is empty then we do not get nil but 0

String into sum

str='1,2,3,4'.split(',').map(&:to_i).inject(0,:+) #1+2+3+4=10

Array of numbers into sum

 num=[1,2,3,4].inject(0,:+)#=>10
 p str
 p num

Upvotes: 2

yiliangt5
yiliangt5

Reputation: 1

I think you can use either of following statements:

array.map(&:to_f).reduce(:+)
array.sum(&:to_f)

Upvotes: -1

Arup Rakshit
Arup Rakshit

Reputation: 118289

You just need to do

array.map(&:to_f).reduce(:+)

Explanation :-

# it give you back all the Float instances from String instances
array.map(&:to_f)
# same as
array.map { |string| string.to_f }
array.map(&:to_f).reduce(:+)
# is a shorthand of 
array.map(&:to_f).reduce { |sum, float| sum + float }

Documentation of #reduce and #map.

Upvotes: 19

Bala
Bala

Reputation: 11274

a = ["12.4", "48.2"]
a.inject(0) {|s,e| s.to_f + e.to_f } #=> 60.6

inject lets you accumulate a value across. Documentation of #inject

Upvotes: 1

Related Questions