learns_to divide by zero

| | Comments (4)

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: , , , , , , ,

Categories

4 Comments

Finger in Tim Harrington's Nose said:

As a non-fun person (read android):

This is part of the IEEE 754 standard for floats, and ruby obeys it as every other modern language out there does.

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/5156

matt said:

If you're validates_inclusion_of :foo, :in => RANGE, why can't you make that range positive?

If it just needs to be a positive number, why not validates_inclusion_of :foo, :minimum => 0 ?

matt said:

ack, nevermind on that last one. my lack of coffee while reading my morning rss caused me to misread the api.

Greg said:

Yeah. . .unfortunately there's only :in and it takes an innumerable:

Here's the caboo.se edge docs for validates_inclusion_of.

Leave a comment

About this Entry

This page contains a single entry by published on April 6, 2006 12:19 AM.

learns_to: A None-Too-Brief Introduction to Partials was the previous entry in this blog.

Back from the Lull is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 4.0
Clicky Web Analytics