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.
Ruby | Enumerable sum() function The sum() of enumerable is an inbuilt method in Ruby returns the sum of all the elements in the enumerable.
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.
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
.
str='1,2,3,4'.split(',').map(&:to_i).inject(0,:+) #1+2+3+4=10
num=[1,2,3,4].inject(0,:+)#=>10
p str
p num
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With