Skip to content

Instantly share code, notes, and snippets.

@faizaanshamsi
Last active December 28, 2015 09:29
Show Gist options
  • Save faizaanshamsi/7479036 to your computer and use it in GitHub Desktop.
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.
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" ) , "================"
@jzgit
Copy link

jzgit commented Nov 18, 2013

this is a good - I would start to pull out methods as a next step. So for instance these:

    if !price.match(/\A\d+(\.\d+)?\z/)
        puts "Please put in a real price!"
    else
        all_prices << price.to_f
    end

    if !amount_tendered.match(/\A\d+(\.\d+)?\z/)
        puts "That's not real money! Try again!"
    else
        total_tendered += amount_tendered.to_f
    end

could be changed to:

   def not_real_money?(input)
      !input.match(/\A\d+(\.\d+)?\z/)
   end

   if not_real_money?(amount_tendered)
    puts "That's not real money! Try again!"
   else
       total_tendered += amount_tendered.to_f
   end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment