In Ruby, dividing by zero doesn't always raise a ZeroDivisionError

October 20, 2012

Usually when you try and divide by zero, Ruby (and every other language) will raise and “divided by zero” error. Like this:

1.9.3-p194> 0/0
ZeroDivisionError: divided by 0
        from (irb):1:in `/'

Or like this:

1.9.3-p194 > [0/0, 1].min
ZeroDivisionError: divided by 0
        from (irb):2:in `/'

Where things get a little weird is if you use Floats. This time Ruby doesn’t return an error, but instead returns the NaN constant.

1.9.3-p194> 0/0.0
 => NaN 

When you combine this with .min then you get an error that, IMHO, isn’t very accurate.

1.9.3-p194> [0/0.0, 1].min
ArgumentError: comparison of Fixnum with Float failed
        from (irb):3:in `each'
        from (irb):3:in `min'

Even worse is when both arguments are Floats. How can a comparision of two Floats fail?

1.9.3p194> [0/0.0, 1.0].min
ArgumentError: comparison of Float with Float failed
        from (irb):1:in `each'

I think it’s interesting that if you compare those two elements directly, you don’t get an error at all.

1.9.3-p194> 0/0.0 <=> 1
 => nil 

Note: This issue is also present in Ruby 1.8.7.