Skip to content

Instantly share code, notes, and snippets.

@ryanswood
Created July 9, 2014 21:49
Show Gist options
  • Select an option

  • Save ryanswood/c878a38cac2b835573b1 to your computer and use it in GitHub Desktop.

Select an option

Save ryanswood/c878a38cac2b835573b1 to your computer and use it in GitHub Desktop.
class ChangeDispenser
attr_reader :purse
MONEY_TO_VALUE = {
quarter: 25,
dime: 10,
nickel: 5,
penny: 1
}
def initialize
@purse = Hash.new(0)
end
def add_cents(cents)
MONEY_TO_VALUE.each do |coin, value|
coin_qty = cents / value
@purse[coin] += coin_qty
cents -= (coin_qty * value)
end
end
def dispense
# Dispensing should clear the purse not just return the calculcated change everytime.
# One way to do that is to copy the value of @purse and then clear the purse
# Other way is to try the Hook gem to act as a callback. (haven't tried this yet.)
change = @purse.clone
@purse.clear
change
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment