Created
January 22, 2018 17:04
-
-
Save rodloboz/a0cbabb214589dc7b3e5a6000729cd7a to your computer and use it in GitHub Desktop.
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
| # Welcome the user | |
| # Display the stock/list of products | |
| # Get user choice | |
| # ask quantity | |
| # save quantity | |
| # Check if it's available | |
| # Add to cart | |
| # Ask if they want continue shoppinh | |
| # Add total and display bill | |
| def calculate_total(cart) | |
| # total = 0 | |
| # CART.each { |_key, value| total += value } | |
| cart.reduce(0) { |total, (item, quantity)| total += quantity * STORE[item] } | |
| end | |
| STORE = { | |
| "kiwi" => 1.25, | |
| "banana" => 0.50, | |
| "mango" => 4.00, | |
| "aspargus" => 9.00 | |
| } | |
| CART = {} | |
| puts "Welcome to Instacart" | |
| puts "********************" | |
| puts "\n\n" # \n added a new line | |
| STORE.each do |item, value| | |
| # sprintf "%.2f", value <==> sprintf("%.2f", value) | |
| puts "#{item}: #{sprintf "%.2f", value} €" | |
| end | |
| loop do | |
| puts "Which item? (or 'quit' to checkout)" | |
| choice = gets.chomp | |
| break if choice == "quit" | |
| if STORE.key?(choice) | |
| puts "How many?" | |
| quantity = gets.chomp | |
| until quantity.match(/\d/) | |
| puts "Please type a valid amount" | |
| quantity = gets.chomp | |
| end | |
| # CART[choice] = STORE[choice] # e.g. STORE['kiwi'] => 1.25 | |
| CART[choice] = quantity.to_i | |
| else | |
| puts "Sorry, we don't have #{choice} today." | |
| end | |
| end | |
| # Checkout | |
| puts "-------BILL---------" | |
| puts "Item | Amount | Cost" | |
| CART.each do |item, quantity| | |
| puts "#{item} x #{quantity} : #{sprintf "%.2f", quantity * STORE[item]} €" | |
| end | |
| puts "TOTAL: #{calculate_total(CART)} €" | |
| puts "--------------------" | |
| puts "Thank you for shopping" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment