Question

I am fairly new to RoR. I have the following codes and uses a simple summation and division, but the value I get is 0. Not sure where I went wrong. Thx

- capacity_left = (total_capacity / total_amps) rescue 0
  h4 = "Capacity Reserve Left:  #{capacity_left} Hrs "

- total_amps = @site.equipment_inventories.sum {|e| e.equipment.amp.amp }
      h5 = "Total Amps: #{total_amps} amp"

- total_capacity = @site.dc_power_inventories.sum {|d| d.dc_power_supply.battery.capacity.capacity }
      h5 = "Total Capcity: #{total_capacity} Amp/hr"
Was it helpful?

Solution

Flip your code as below:

- total_amps = @site.equipment_inventories.sum {|e| e.equipment.amp.amp }
      h5 = "Total Amps: #{total_amps} amp"

- total_capacity = @site.dc_power_inventories.sum {|d| d.dc_power_supply.battery.capacity.capacity }
      h5 = "Total Capcity: #{total_capacity} Amp/hr"

- capacity_left = (total_capacity / total_amps) rescue 0
  h4 = "Capacity Reserve Left:  #{capacity_left} Hrs "

total_capacity and total_amps MUST be set before using.

Currently, as total_capacity and total_amps are not defined there value is nil. Dividing nil by nil raises error undefined method '/' for nil:NilClass BUT since you rescued it using rescue 0, the output is always 0.

OTHER TIPS

most probably both your variables are integers so you perform an integer division.

10 / 3 = 3
3 / 10 = 0

what you need to do is make a float cast, that can be done with the to_f method, and needs to be done to only one of the divisions operands.

so in your case

total_capacity / total_amps.to_f

or

total_capacity.to_f / total_amps

will both operate a float division and give a float result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top