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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)