Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Numeric#modulo

(::Numeric) -> ::Numeric
modulo(p1)

Alias of #%

Returns self modulo other as a real number.

Of the Core and Standard Library classes, only Rational uses this implementation.

For Rational r and real number n, these expressions are equivalent:

Example
r % n
r-n*(r/n).floor
r.divmod(n)[1]

See Numeric#divmod.

Examples:

Example
r = Rational(1, 2)    # => (1/2)
r2 = Rational(2, 3)   # => (2/3)
r % r2                # => (1/2)
r % 2                 # => (1/2)
r % 2.0               # => 0.5

r = Rational(301,100) # => (301/100)
r2 = Rational(7,5)    # => (7/5)
r % r2                # => (21/100)
r % -r2               # => (-119/100)
(-r) % r2             # => (119/100)
(-r) %-r2             # => (-21/100)
See also #% #magnitude #negative? #integer? also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0