Last active
July 8, 2019 16:21
-
-
Save SalahHamza/e0d953f0b9770c65b9e4b19986a7276f 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
store = { | |
apple: { | |
price: 2, | |
quantity: 40 | |
}, | |
pineapple: { price: 3, quantity: 80}, | |
strawberry: { price: 6, quantity: 60}, | |
} | |
# greeting the user | |
puts "Welcome to Instacart" | |
puts "These are our items:" | |
# showing the store items | |
store.each do |fruit, detail| | |
# detail is a hash with the fruits details (price, quantity) | |
puts "#{fruit}: #{detail[:price]}€ - #{detail[:quantity]} availabe" | |
end | |
# a hash with a default value of 0 | |
# This will prevent the code from "throwing" | |
# an error in case we add up the quantities later | |
cart = Hash.new(0) | |
item = nil | |
while item != :quit | |
puts "Which item do you want? (or quit to checkout):" | |
item = gets.chomp.to_sym | |
# check if the fruit exists | |
# if store.keys?(item) | |
if store[item].nil? | |
if item != :quit | |
puts "Fruit doesn't exist." | |
end | |
else | |
puts "Hom many do you need?" | |
quantity = gets.chomp.to_i | |
# we need to check if the store has that many items | |
if quantity <= store[item][:quantity] | |
# add the item to the cart with the quantity as a value | |
cart[item] += quantity | |
# Substracting the bought quantity from the store's quantity (availability) | |
store[item][:quantity] -= quantity | |
else | |
puts "Ooops! We don't have that many #{item}" | |
puts "we only have #{store[item][:quantity]}" | |
end | |
end | |
end | |
puts "-------------BILL-------------" | |
total = 0 | |
cart.each do |fruit, quantity| | |
fruit_price = quantity * store[fruit][:price] | |
puts "#{fruit}: #{quantity} X #{store[fruit][:price]}€ = #{fruit_price}€" | |
total += fruit_price | |
end | |
puts "TOTAL: #{total}€" | |
puts "-----------------------------" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment