
Untitled
By: a guest on
Aug 3rd, 2012 | syntax:
None | size: 1.52 KB | hits: 9 | expires: Never
#### 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)
puts second_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}."
#