Reputation: 553
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
Reputation: 71
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
Upvotes: 2
Reputation: 1
I think you can use either of following statements:
array.map(&:to_f).reduce(:+)
array.sum(&:to_f)
Upvotes: -1
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