Is it just me, or is it fun when you get to break basic rules you learned in school? And more fun the younger you learned them? Not sharing, not looking both ways before crossing the street, not eating cookies and ice cream in bed before going to sleep without brushing your teeth, and so on.
Last week, at work, I got to divide by zero.
Here's the setup. We wanted to make sure that some value was positive, but we couldn't use a normal greater-than-zero comparison because the Rails situation demanded either a range or an array (it was a validates_inclusion_of :some_value, :in => range, if you're curious).
Anyway, there's the problem: how do you get a range that includes all numbers from zero on up? In mathematical terms, what I wanted was: [0,∞). So, I needed infinity. After staring blankly for awhile, it occurred to me: divide by zero! That would certainly produce something odd, possibly even infinity. I tried it:
>> 1/0
ZeroDivisionError: divided by 0
from (irb):16:in `/'
from (irb):16
Ow, snap! Ruby's not having any of that. But don't fear, not all options are exhausted. There are different kinds of one, different kinds of zero. And it turns out, that's the key. For some reason, Ruby won't even think about dividing an integer by zero, but give it a float, and it gets creative:
=>> 1.0/0
=> Infinity
Infinity! What's this? It looks a lot like a constant, but no:
>> (1.0/0).class
=> Float
It's a float. Which is just what ranges take as their bounds. And now we've got it:
>> range = 0..1.0/0
=> 0..Infinity
>> range.include?(1000000000000000000 * 100000000000000000)
=> true
Nifty? Subversive? Dangerous? Maybe. Fun? I think so.
Tagged: infinity, ruby, rails, programming, division, zero, numbers, math