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

Untitled

By: a guest on Aug 3rd, 2012  |  syntax: None  |  size: 1.52 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. puts second_cart.inspect
  62.  
  63.  
  64. # #### 3 ####
  65. # # Purchase details ##
  66. #
  67. #cart.items.each do |item|
  68. #  puts "#{item.product} - #{item.quantity} - #{item.price} US$"
  69. #end
  70. #
  71. # #### 4 ####
  72. # # Sum total value in the cart ##
  73.  
  74. #puts "The total of your shopping cart is: #{cart.total_cart_value}"
  75. #
  76. # #### 5 ####
  77. # ## Discounts: iPods 2 x 1, iMac => (iPhone - 20%) ##
  78. # puts "You are qualified for the discounted amount of: $#{cart.discount}."
  79. # puts "The total of your purchase is $#{cart.total}."
  80. #