Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 3rd, 2012  |  syntax: None  |  size: 1.98 KB  |  hits: 9  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #### 1 ####
  2. ## Inventory ##
  3.  
  4. class Product
  5.  
  6.   attr_accessor :name, :price
  7.  
  8.   def initialize(name, price)
  9.     @name = name
  10.     @price = price
  11.   end
  12.  
  13. end
  14.  
  15. iPod = Product.new('iPod', 229.00)
  16. iMac = Product.new('iMac', 1199.00)
  17. iPhone = Product.new('iPhone', 49.00)
  18.  
  19.  
  20. # #### 2 ####
  21. # ## Add to cart ##
  22.  
  23. class Item
  24.  
  25.   attr_accessor :name, :quantity
  26.  
  27.   def initialize(name, quantity)
  28.     @name = name
  29.     @quantity = quantity
  30.   end
  31.    
  32. end
  33.  
  34. class Cart
  35.  
  36.   attr_accessor :products
  37.  
  38.   def initialize
  39.     @products = []
  40.   end
  41.  
  42.   def add_to_cart(product, quantity=1)
  43.     i = self.products.index { |x| x.name == product }
  44.     i.nil? ? @products << Item.new(product, quantity) : self.products[i].quantity += quantity
  45.   end
  46.  
  47. end
  48.  
  49. cart = Cart.new()
  50. second_cart = Cart.new()
  51.  
  52. cart.add_to_cart(iMac, 5)
  53. cart.add_to_cart(iPhone)
  54. cart.add_to_cart(iPod, 2)
  55.  
  56. second_cart.add_to_cart(iMac,2)
  57. second_cart.add_to_cart(iPod)
  58. second_cart.add_to_cart(iPod)
  59. second_cart.add_to_cart(iPhone,5)
  60.  
  61. # get the list of product in both carts
  62. list = (cart.products + second_cart.products).collect { |x| x.name }.uniq
  63. # go through the list and create a new cart using the quantities from both carts
  64. tot_cart = Cart.new()
  65. list.each { |x|
  66.   c = cart.products.index { |p| p.name == x }
  67.   q1 = c ? cart.products[c].quantity : 0
  68.   sc = second_cart.products.index { |p| p.name == x }
  69.   q2 = sc ? second_cart.products[sc].quantity : 0
  70.   tot_cart.add_to_cart(x, q1+q2)
  71.   }
  72.  
  73. puts tot_cart.inspect
  74.  
  75.  
  76.  
  77. # #### 3 ####
  78. # # Purchase details ##
  79. #
  80. #cart.items.each do |item|
  81. #  puts "#{item.product} - #{item.quantity} - #{item.price} US$"
  82. #end
  83. #
  84. # #### 4 ####
  85. # # Sum total value in the cart ##
  86.  
  87. #puts "The total of your shopping cart is: #{cart.total_cart_value}"
  88. #
  89. # #### 5 ####
  90. # ## Discounts: iPods 2 x 1, iMac => (iPhone - 20%) ##
  91. # puts "You are qualified for the discounted amount of: $#{cart.discount}."
  92. # puts "The total of your purchase is $#{cart.total}."
  93. #