Last Updated: February 25, 2016
·
893
· blacktulip

Numeric#divmod in Ruby

In Ruby, num.divmod(numeric) returns an array containing the quotient and modulus obtained by dividing num by numeric.

So if q, r = x.divmod(y) then

q = floor(x / y)

x = q * y + r

Example: Calculate the combination of [50, 20, 10, 5, 1] dollar notes for a certain amount of money.

def make_change r, notes = [50,20,10,5,1]
  notes.map do |c|
    q, r = r.divmod c
    q
  end
end