Skip to content

Instantly share code, notes, and snippets.

@jwoertink
Created November 16, 2019 18:39
Show Gist options
  • Save jwoertink/f99a78e438f6c1881d14eff7c84742c6 to your computer and use it in GitHub Desktop.
Save jwoertink/f99a78e438f6c1881d14eff7c84742c6 to your computer and use it in GitHub Desktop.
class Basket
attr_accessor :items
def initialize
self.items = []
end
def total
self.items.sum(0.0) { |item| item[:price] }
end
def add(item)
self.items << item
end
def remove(item_index)
self.items.delete_at(item_index)
end
end
def add_item_menu(choice)
selected_item = @items[choice - 1]
@basket.add(selected_item)
total = @basket.total
puts "Your basket total is: $#{total}"
end
def remove_item_menu
puts "Which item do you want to remove?"
@basket.items.each_with_index do |item, index|
puts "#{index + 1}) #{item[:name]}"
end
print "> "
choice = gets.chomp.to_i
removed_item = @basket.remove(choice - 1)
puts "Removed #{removed_item[:name]}"
puts "Basket total: #{@basket.total}"
end
@items = [
{:name => "Milk", :price => 2.5},
{:name => "Cheese", :price => 1}
]
@basket = Basket.new
puts "Welcome to the store"
puts "Choose an item to put in your basket"
@items.each_with_index do |item, index|
puts "#{index + 1}) #{item[:name]} - $#{item[:price]}"
end
puts "q) Leave the store"
puts "r) Remove an item"
puts "l) List basket items"
loop do
print "> "
choice = gets.chomp
case choice.downcase
when "q"
break
when "r"
remove_item_menu
when "l"
list_basket_menu
when /\d+/
add_item_menu(choice.to_i)
else
puts "That doesn't look like a valid option"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment