Search code examples
ruby-on-railstypesdivisionrational-numbers

Sudden rational result from devision in Ruby on Rails


When doing the devision in IRB:

6/3600

the result is always 0.

But in a live Rails application running in WEBrick or Apache/Passenger the same division results in 1/600 value of type Rational.

I am getting the same Rational result when doing division in a breakpoint's watch in RubyMine 6.3.3

Both arguments are always Integer.


Solution

  • This has to do with the mathn module. For some reason it's not loaded in your IRB, but it's loaded by something in your server session and probably from a debugging gem in the RubyMine debug session as well.

    The behaviour you experienced is documented here: http://www.ruby-doc.org/stdlib-2.1.1/libdoc/mathn/rdoc/Numeric.html

    You can test this in your IRB session. 6/3600 results in 0. After you loaded mathn with require 'mathn' you get another result. It will be (1/600) instead.

    You can also force each situation, to make your code more robust at this point. If you want a rational result anyway you can do something like 6/3600.to_r or vice versa if mathn is loaded (6/3600).to_i. Another way to make a division explicit is to use the method div().

    Here a dump of an IRB session, which is a conclusion of the text above.

    >> 6/3600
    0
    
    >> 6/3600.to_r
    (1/600)
    
    >> require 'mathn'
    true
    
    >> 6/3600
    (1/600)
    
    >> (6/3600).to_i
    0
    
    >> 6.div(3600)
    0
    

    This topic is also discussed here: https://bugs.ruby-lang.org/issues/2121