mhenrixon
mhenrixon

Reputation: 6278

Rescuing a DivisionByZero with default value returns NaN in 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

Upvotes: 4

Views: 1919

Answers (3)

Arup Rakshit
Arup Rakshit

Reputation: 118271

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?

Upvotes: 11

Michał Szajbe
Michał Szajbe

Reputation: 9002

You can simplify your code:

ratio = total_amount == 0 ? 0 : bet_money_amount_cents.to_f / total_amount

Upvotes: 3

falsetru
falsetru

Reputation: 369094

Because 0.0 / 0.0 yields Float::NAN (Nan) instead of throwing ZeroDivisionError exception (unlike 0 / 0)

0.0 / 0.0
# => NaN
0.0 / 0
# => NaN
0 / 0
# ZeroDivisionError: divided by 0
#         from (irb):17:in `/'
#         from (irb):17
#         from C:/Ruby200-x64/bin/irb:12:in `<main>'

According to ZeroDivisionError documentation:

Raised when attempting to divide an integer by 0.

Upvotes: 4

Related Questions