-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathshopping_cart.rb
More file actions
47 lines (37 loc) · 834 Bytes
/
shopping_cart.rb
File metadata and controls
47 lines (37 loc) · 834 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Product
attr_reader :name, :price
def initialize(name, price)
@name = name
@price = price
end
end
class Cart
def initialize
@products = []
end
def add_product(product)
@products << product
end
def add_products(products)
@products += products
end
def contents
@products.each do |product|
puts "#{product.name}: $#{product.price}"
end
end
def sub_total
@products.reduce(0) do |sum, product|
product.price + sum
end
end
end
coffee = Product.new("coffee", 16.25)
creamer = Product.new("creamer", 3.5)
sugar = Product.new("sugar", 2.25)
chocolate_syrup = Product.new("chocolate syrup", 2.23)
cart = Cart.new
cart.add_products([coffee, creamer, sugar, chocolate_syrup])
cart.contents
puts "---------------------"
puts "Subtotal: $#{cart.sub_total}"