- #### 1 ####
- ## Inventory ##
- class Product
- attr_accessor :name, :price
- def initialize(name, price)
- @name = name
- @price = price
- end
- end
- iPod = Product.new('iPod', 229.00)
- iMac = Product.new('iMac', 1199.00)
- iPhone = Product.new('iPhone', 49.00)
- # #### 2 ####
- # ## Add to cart ##
- class Item
- attr_accessor :name, :quantity
- def initialize(name, quantity)
- @name = name
- @quantity = quantity
- end
- end
- class Cart
- attr_accessor :products
- def initialize
- @products = []
- end
- def add_to_cart(product, quantity=1)
- i = self.products.index { |x| x.name == product }
- i.nil? ? @products << Item.new(product, quantity) : self.products[i].quantity += quantity
- end
- end
- cart = Cart.new()
- second_cart = Cart.new()
- cart.add_to_cart(iMac, 5)
- cart.add_to_cart(iPhone)
- cart.add_to_cart(iPod, 2)
- second_cart.add_to_cart(iMac,2)
- second_cart.add_to_cart(iPod)
- second_cart.add_to_cart(iPod)
- second_cart.add_to_cart(iPhone,5)
- # get the list of product in both carts
- list = (cart.products + second_cart.products).collect { |x| x.name }.uniq
- # go through the list and create a new cart using the quantities from both carts
- tot_cart = Cart.new()
- list.each { |x|
- c = cart.products.index { |p| p.name == x }
- q1 = c ? cart.products[c].quantity : 0
- sc = second_cart.products.index { |p| p.name == x }
- q2 = sc ? second_cart.products[sc].quantity : 0
- tot_cart.add_to_cart(x, q1+q2)
- }
- puts tot_cart.inspect
- # #### 3 ####
- # # Purchase details ##
- #
- #cart.items.each do |item|
- # puts "#{item.product} - #{item.quantity} - #{item.price} US$"
- #end
- #
- # #### 4 ####
- # # Sum total value in the cart ##
- #puts "The total of your shopping cart is: #{cart.total_cart_value}"
- #
- # #### 5 ####
- # ## Discounts: iPods 2 x 1, iMac => (iPhone - 20%) ##
- # puts "You are qualified for the discounted amount of: $#{cart.discount}."
- # puts "The total of your purchase is $#{cart.total}."
- #