Skip to content

Why am I getting a NoMethodError: undefined method `&' for Rational?

Gabriel Fortuna edited this page Jun 21, 2021 · 1 revision

TL;DR - Something is using mathn somewhere in your code. You should consider upgrading to Ruby 2.5+ where mathn is deprecated.

Please see Issue 373 for more information.

How this issue manifests itself

When writing encrypted zip files, you may occasionally have an exception raised that looks similar to the subject of this page. Retrying the exact same operation will normally complete without an exception after a few attempts.

Why this issue occurs

You are probably requiring, or using a gem that requires the mathn library. A common culprit is the amazingly useful ruby-units gem.

mathn appears to do some monkey patching which causes mischief for libs like this one.

How to fix this issue

The dumb way

If we're being monkey-patched, we'll just monkey patch you right back:

class Rational
  def &(int)
    self.to_i & int
  end
end

The smart way

The mathn lib was deprecated in Ruby 2.2 and removed entirely in 2.5. Upgrade to a currently maintained (as of mid-2021) Ruby release (2.7+ or 3.x)