Created
July 28, 2025 20:22
-
-
Save RobertoBarros/627b2cddfb790fea455e3ccaa49ddf75 to your computer and use it in GitHub Desktop.
batch 2100 - Reboot - Instacart - Part 3 final
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
| require 'colored' # permite utilizar cores nas strings, como .red | |
| # mensagem de boas vindas | |
| puts ("-" * 30).yellow | |
| puts "Welcome to Instacart".yellow | |
| puts ("-" * 30).yellow | |
| store = { | |
| "kiwi" => {price: 1.25, stock: 5}, | |
| "banana" => {price: 0.5, stock: 4}, | |
| "mango" => {price: 4, stock: 1}, | |
| "asparagus" => {price: 9, stock: 5} | |
| } | |
| cart = [] | |
| # LOOP até o `quit` | |
| loop do | |
| # Apresentar os produtos com o respectivo preço e estoque | |
| puts "In our store today" | |
| # info é hash no formato {price: 1.25, stock: 5} | |
| store.each do |item, info| | |
| puts "#{item}: #{info[:price]}€ (#{info[:stock]} available)" | |
| end | |
| puts "-" * 30 | |
| # Perguntar o produto ou `quit` | |
| puts "Which item? (or 'quit' to checkout)".bold.blue | |
| product = gets.chomp.downcase | |
| break if product == "quit" | |
| if store.key?(product) | |
| # Perguntar a quantidade | |
| puts "How many ?" | |
| quantity = gets.chomp.to_i | |
| # Temos a quantidade do produto em estoque? | |
| available = store[product][:stock] | |
| if quantity <= available | |
| # Adicionar ao carrinho produto e quantidade | |
| # cart é um array de hashes no formato: | |
| # [{name: "kiwi", quantity: 2},{name: "mango", quantity: 5},{name: "banana", quantity: 3}] | |
| cart << {name: product, quantity: quantity} | |
| # Remover a quantidade do estoque | |
| store[product][:stock] -= quantity | |
| else | |
| puts "Sorry, there are only #{available} #{product} left.".red | |
| end | |
| else | |
| # Mostrar erro se produto inexistente | |
| puts "sorry, we don't have #{product} today".red | |
| end | |
| # FIM DO LOOP | |
| end | |
| # Somar os valores dos produtos no carrinho | |
| sum = 0 | |
| puts ("-" * 10) + "Bill" + ("-" * 10) | |
| # product é um hash no formato {name: "kiwi", quantity: 2} | |
| cart.each do |product| | |
| name = product[:name] | |
| quantity = product[:quantity] | |
| price = store[name][:price] | |
| subtotal = price * quantity | |
| sum += subtotal | |
| # Mostrar o subtotal no formato: kiwi: 2 X 1.25€ = 2.5€ | |
| puts "#{name}: #{quantity} x #{price}€ = #{subtotal}€".green | |
| end | |
| # Mostrar o total | |
| puts "TOTAL: #{sum}€".bold.green | |
| puts "-" * 30 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment