Last active
December 28, 2015 09:29
-
-
Save faizaanshamsi/7479036 to your computer and use it in GitHub Desktop.
Ruby Fundamentals II. This Cash register takes multiple items, returns the total, then sums up multiple tendered amounts till the total is met and returns the change.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
all_prices = [] | |
price = "" | |
until price == "done" do | |
puts "What is the sale price?" | |
price = gets.chomp | |
if !price.match(/\A\d+(\.\d+)?\z/) | |
puts "Please put in a real price!" | |
else | |
all_prices << price.to_f | |
end | |
end | |
subtotal = all_prices.inject(0) {|sum, i| sum + i} | |
puts "Here are your item prices: \n" | |
all_prices.each {|x| puts "$#{sprintf('%.2f', (x))}"} | |
puts "The total amount due is $#{sprintf('%.2f', (subtotal))}" | |
amount_tendered = 0 | |
total_tendered = 0 | |
until total_tendered >= subtotal do | |
puts "What is the amount tendered?" | |
amount_tendered = gets.chomp | |
if !amount_tendered.match(/\A\d+(\.\d+)?\z/) | |
puts "That's not real money! Try again!" | |
else | |
total_tendered += amount_tendered.to_f | |
end | |
puts "You've given me $#{sprintf('%.2f', (total_tendered))} so far! \n Give me $#{sprintf('%.2f', (subtotal - total_tendered))} more!" unless subtotal - total_tendered <= 0 | |
end | |
puts "===Thank You!===", "The total change due is $#{sprintf('%.2f', (total_tendered.to_f - subtotal))}", | |
"", Time.now.strftime("%m/%d/%Y %I:%M%p" ) , "================" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this is a good - I would start to pull out methods as a next step. So for instance these:
could be changed to: