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
Written by Qing Wang
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#