Skip to content

Instantly share code, notes, and snippets.

@volpeo
Created July 10, 2018 11:01
Show Gist options
  • Save volpeo/9099660c62af8895c21422606e067ad0 to your computer and use it in GitHub Desktop.
Save volpeo/9099660c62af8895c21422606e067ad0 to your computer and use it in GitHub Desktop.
$products = [
{
name: "kiwi",
price: 5,
stock: 20
},
{
name: "banane",
price: 3,
stock: 3
},
{
name: "orange",
price: 2,
stock: 150
}
]
$cart = []
def display_menu
puts "---------- INSTACART ----------"
puts "1. Lister le catalogue"
puts "2. Ajouter un produit"
puts "3. Retirer un produit"
puts "4. Imprimer la facture"
puts "5. Exit"
end
def list_products
puts "-" * 30
$products.each_with_index do |product, index|
puts "#{index + 1}) #{product[:name]} - #{product[:price]}€ (#{product[:stock]})"
end
end
def add_product
print "product index?> "
product_index = gets.to_i - 1
selected_product = $products[product_index].clone
return puts "Ce produit n'existe pas" unless selected_product
print "how many?> "
quantity = gets.to_i
if quantity > selected_product[:stock]
quantity = selected_product[:stock]
puts "On t'a tout mis"
end
selected_product[:quantity] = quantity
selected_product.delete(:stock)
$cart << selected_product
$products[product_index][:stock] -= quantity
end
def print_bill
$cart.each_with_index do |product, index|
puts "#{index + 1}) #{product[:name]} - #{product[:price]}€ x #{product[:quantity]}"
end
total = $cart.reduce(0) do |sum, product|
sum += product[:quantity] * product[:price]
end
puts "TOTAL:...........#{total}€"
end
def remove_product
print "product index?>"
product_index = gets.to_i - 1
$cart.delete_at(product_index)
end
loop do
display_menu
print "action?> "
user_action = gets.to_i
case user_action
when 1 then list_products
when 2 then add_product
when 3 then remove_product
when 4 then print_bill
when 5 then break
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment