Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 826
Steve_D Avatar asked Jun 10 '14 18:06

Steve_D


People also ask

How do you sum an array value in Ruby?

Ruby | Enumerable sum() function The sum() of enumerable is an inbuilt method in Ruby returns the sum of all the elements in the enumerable.

How do you slice an array in Ruby?

The array. slice() is a method in Ruby that is used to return a sub-array of an array. It does this either by giving the index of the element or by providing the index position and the range of elements to return.


2 Answers

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.

like image 168
Arup Rakshit Avatar answered Sep 24 '22 12:09

Arup Rakshit


  • 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
like image 37
Frank Avatar answered Sep 26 '22 12:09

Frank