My Site
Categories
Blogs
Useful Links
Ruby oddities (or "what's 1.0 divided by 0.0?")
Written by: Johannes Sasongko (sjohannes)

Working very closely with the source code of MRI (Matz's Ruby Implementation, a term used to distinguish the main Ruby implementation from the language itself) has exposed me to some of Ruby's most... interesting behaviour. This is one:

irb(main):001:0> 1.0 / 0.0
=> Infinity
irb(main):002:0> 1.0.divmod(0.0)[0]
=> NaN
irb(main):003:0> 1.0.div(0.0)
FloatDomainError: Infinity
        from (irb):3:in `div'
        from (irb):3:in `div'
        from (irb):3


And no, Infinity does not equal NaN, and they're not related in terms of inheritance or anything like that; they're completely different values. Apparently, @/@ follows the IEEE-754 standard (including in cases involving a negative zero), @divmod@ probably follows intuitive mathematics (which I'm quite sure is not really correct because "1 / 0" has no meaning in strict mathematics), while @div@ follows a practice quite common in programming languages of raising an exception (though an odd one at that). Coupled with the fact that @1 / 0@ raises a different exception (ZeroDivisionError), well... go figure.

vim tip: Modelines

In Vim, you can set per-file options using modelines. (This has nothing to do with the term "mode line" in Emacs. Emacs has a similar feature, but I don't know what it's called there.) Basically they are special strings in the first or last few lines of a file that Vim interprets into options. They look like, for example, @// vim: expandtab@. The exact syntax is explained in detail in the "modeline":http://vimdoc.sourceforge.net/htmldoc/options.html#modeline section of Vim's help.

File under: Programming
Comments:

No comments have been added yet


Add a comment:

Name:
Type Vim Here:   (It's a human test)
Email Address:   (optional for reply subscription)
Comment:   
 
Note: If you enter your email address, you will be subscribed to this article and will recieve comment updates via email. This is the only thing your address will be used for. A link will be provided at the end of each email that will allow you to unsubscribe should you need to, or you can go to http://www.vimtips.org/unsubscribe to unsubscribe from any/all updates.