Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rescuing a DivisionByZero with default value returns NaN in ruby?

Tags:

ruby

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
like image 489
mhenrixon Avatar asked Dec 02 '22 20:12

mhenrixon


1 Answers

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?
like image 128
Arup Rakshit Avatar answered Mar 26 '23 02:03

Arup Rakshit