Library contents

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

  1. Start with 7 and 3
  2. Do this Find quotient and remainder
  3. Result 2 and 1
Two times three plus one reconstructs seven.

Syntax

Ruby 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.

First output line2 packs, 1 left
lesson.rb
[13, -13].each do |units|
  packs, left = units.divmod(6)
  puts "#{packs} packs, #{left} left"
end
Output
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

Advertisements

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.

Given29 tubes · 6 per set
Worked result4 sets

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.

Given40 tickets · 8 groups
Worked result5 tickets

Every ticket is allocated because the division has zero remainder.