Ruby Integer#divmod
Integer#divmod returns the floor quotient and modulo remainder as a pair. For a positive divisor, the remainder is between zero and one less than the divisor.
A simple example
Integer#divmod
- Start with 7 and 3
- Do this Find quotient and remainder
- Result 2 and 1
Syntax
quotient, remainder = units.divmod(pack_size)
Run this example in Ruby
Save the program as lesson.rb. Use Ruby 2.6 or later.
ruby lesson.rb
Split a signed balance into whole units and a remainder
An account balance can be negative as well as positive. Split it into whole units and a remainder under the stated division convention so the two parts reconstruct the original amount.
[13, -13].each do |units|
packs, left = units.divmod(6)
puts "#{packs} packs, #{left} left"
end
2 packs, 1 left -3 packs, 5 left
The identity units = quotient * pack_size + remainder still holds for a negative balance. With a positive divisor, −13 becomes three negative packs plus five units.
Ruby documentation for Integer#divmod
Make complete paint sets
A studio has 29 paint tubes and puts six in each set. It lists only sets that can be handed out complete.
Four sets use 24 tubes. Five tubes stay on the shelf.
Share a complete batch of tickets
Forty tickets are shared equally among eight activity groups. The organizer records the whole-number share per group.
Every ticket is allocated because the division has zero remainder.