Lesson contents

Ruby — Variables and integer division with divmod

Ruby Integer#divmod returns a pair containing the quotient and remainder. With a divisor of 100, it separates an integer price into dollars and cents.

A simple example

Change a stored number

  1. Start with n starts at 2
  2. Do this Add 1 to n
  3. Result 3
After the assignment, reading the same variable gives its new value.
lesson.rb
n = 2
n += 1
puts n
Output
3
Advertisements

Calculate a receipt in cents

Ruby integers grow as needed. divmod returns two integers, and parallel assignment gives each a name. format displays the remainder in a two-character field.

Notebooks: 3 × 125¢ = 375¢. Delivery: 50¢. Amount to pay: 425¢.
Check a stationery order

A student buys three notebooks at 125 cents each. Add the 50-cent delivery charge once for the whole order. Keeping the arithmetic in cents makes the total easy to check against the receipt.

Run the example

Ruby 2.7 or later. Run these commands from the directory containing the example.

ruby lesson.rb
lesson.rb
price_cents = 125
quantity = 3
total = price_cents * quantity + 50
dollars, cents = total.divmod(100)
puts format("%d.%02d", dollars, cents)
Output
4.25

Three items at 125 cents cost 375 cents. Adding one 50-cent delivery charge gives 425 cents. The quotient and remainder on division by 100 give 4 dollars and 25 cents.

Try it yourself

What happens if each item costs 101 cents?

Check your answer

Three items plus delivery cost 353 cents, so the output becomes 3.53.

Ruby language documentation

Related tags

  • Ruby
  • integers
  • variables
  • arithmetic