I have 0.0 24.0 0.0 12.0 0.0 0.0 0.0 0.0 0.0
how do i get the sum of these values? .sum etc do not work on floats
EDIT:
Im doing
<% @data.each do |data| %>
<%= data[ :values ]%>
<%end%>
Where data[:values]
prints
[5.0, 0.0, 0.0, 0.0, 0.0]
[4.0, 0.0, 0.0, 0.0, 0.0]
[1.0, 0.0, 0.0, 0.0, 0.0]
and i only want to get the first value of each array and sum them together to get 10.0
@data prints
[{:name=>"BMW", :values=>[0.0, 0.0, 0.0, 0.0, 0.0]}, {:name=>"Asda", :values=>[32.0, 12.0, 0.0, 0.0, 0.0]}]
Assuming they are in an array, this works:
irb(main):001:0> [0.0, 1.0, 3.0].inject(:+)
=> 4.0
Edit: from your edited question, it appears you want:
@data.reduce(0) { |sum, x| sum += x[:values][0] }
Which grabs the first (0th) element of each :values, and sums them all together:
irb(main):003:0> @data
=> [{:values=>[0.0, 0.0, 0.0, 0.0, 0.0], :name=>"BMW"}, {:values=>[32.0, 12.0, 0.0, 0.0, 0.0], :name=>"Asda"}]
irb(main):004:0> @data.reduce(0) { |sum, x| sum += x[:values][0] }
=> 32.0
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