Skip to content

Instantly share code, notes, and snippets.

@GeoffPurdy
Last active August 29, 2015 14:06
Show Gist options
  • Save GeoffPurdy/470949422b647fe76333 to your computer and use it in GitHub Desktop.
Save GeoffPurdy/470949422b647fe76333 to your computer and use it in GitHub Desktop.
class Currency
def initialize(denominations) # denominatons of currency passed as hash
@denominations = denominations
end
def make_change(amount)
# determine change as minimim possible coinage
@amount = (amount * 100).to_i # convert $ to ¢ //FIXME breaks abstraction
@change = {}
for key in @denominations.keys.sort.reverse # keys MUST to be in desc order
@change[@denominations[key]] = @amount / key # {coinage => quantity}
@amount = Integer(@amount) % key # amount = remaining amount
end
return @change.to_s
end
end
def get_user_input
puts "Enter an amount in dollars and cents [dollars].[cents]
Please omit prepended $ or ¢ symbols
Press only [enter] to quit"
input = gets.chomp
if(0 == input.length) # user hit only enter => exit
puts "adios!"
exit
elsif(input =~ /^\d?(\.\d{2})?$/) # valid format $ || $.¢¢ || .¢¢
return input
else # invalid user input
puts "invalid currency format"
return nil
end
end
while true
amount = get_user_input.to_f
if amount
puts Currency.new({1=>"penny", 5=>"nickel", 10=>"dime", 25=>"quarter", 100=>"dollar"}).make_change(amount)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment