I would expect the begin rescue to set ratio to zero but instead it gets set to NaN
which is incredibly frustrating when I am rescuing the error to provide a default value.
ratio = begin
0.0 / 0.0
rescue ZeroDivisionError
0
end
ratio = 0 if ratio.nan?
The code I would like to get rid of is the ratio = 0 if ratio.nan?
why is that needed?
Edit new code looks like:
ratio = bet_money_amount_cents.to_f / total_amount.to_f
ratio.nan? ? 0 : ratio
Because 0.0 / 0.0
not raising the error(ZeroDivisionError
), you are thinking for.
ZeroDivisionError
is Raised when attempting to divide an integer by 0.
42 / 0
#=> ZeroDivisionError: divided by 0
Note that only division by an exact 0
will raise the exception:
42 / 0.0 #=> Float::INFINITY
42 / -0.0 #=> -Float::INFINITY
0 / 0.0 #=> NaN
I would write as below :
ratio = bet_money_amount_cents.to_f / total_amount.to_f
ratio = 0 if ratio.nan?
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