Ruby's
mathn library
Show archive.org snapshot
changes Fixnum
division to work with exact Rational
s, so
2 / 3 => 0
2 / 3 * 3 => 0
require 'mathn'
2 / 3 => Rational(2,3)
2 / 3 * 3 => 2
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