Read more

Workaround for broken integer division after requiring the mathn library

Tobias Kraze
October 04, 2012Software engineer at makandra GmbH

Ruby's mathn library Show archive.org snapshot changes Fixnum division to work with exact Rationals, so

2 / 3 => 0
2 / 3 * 3  => 0

require 'mathn'
2 / 3 => Rational(2,3)
2 / 3 * 3 => 2
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

While this might sometimes be quite neat, it's a nightmare if this gets required by some gem that suddenly redefines integer division across your whole project. Known culprits are the otherwise excellent distribution Show archive.org snapshot and GetText Show archive.org snapshot gems (the later only when working with mo-files).

To fix this, you can restrict the changes to code parts where you explicitly need them with the attached script. To use it, you first need to wrap the require 'mathn' call (usually by wrapping Bundler.require) like this:

# config/application.rb
MathnWorkaround.intercept do
  Bundler.require(:default, Rails.env) if defined?(Bundler)
  # If you require "mathn" manually, put it inside this block.
end

Afterwards, division is back to normal. To get the exact division, use

2 / 3 => 0
2 / 3 * 3 => 0
MathnWorkaround.with_exact_division do
  2 / 3 => Rational(2,3)
  2 / 3 * 3 => 2
end
Posted by Tobias Kraze to makandra dev (2012-10-04 16:31)