Created
April 19, 2012 21:35
-
-
Save fakefarm/2424359 to your computer and use it in GitHub Desktop.
Code Academy exercise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Make the code below work by creating two classes: Item and Cart. | |
# HINT: It may help to use arrays and hashes inside your Cart class. | |
# Don't worry about sales tax for now. | |
class Item | |
def initialize(name, price) | |
@name = name | |
@price = price | |
end | |
def name | |
@name | |
end | |
def price | |
@price | |
end | |
end | |
class Cart | |
def initialize | |
@my_cart = [] | |
end | |
def items | |
@my_cart | |
end | |
def add(name, qty) | |
my_hash = {:item => name, :quantity => qty} | |
items << my_hash | |
end | |
def total | |
t = 0 # begin the total at 0 | |
@my_cart.each do |hash| # instance variable is passed block, using 'hash' block variable | |
item = hash[:item] # cleaning up the request, moving the specific 'hash item' into simply an item variable. This helps make sure the calculation is clean. | |
price = item.price # moves the price method called on item, into variable | |
quantity = hash[:quantity] # similar to line 52, using hash quantity | |
t += price * quantity # adding the block into the t local variable to calculate the price | |
end # end the block | |
end | |
end | |
# ------------------------------------ | |
# --- Given instances | |
ipad = Item.new("iPad 2", 499) | |
imac = Item.new("iMac 27", 1699) | |
macbook = Item.new("MacBook Air 13", 1299) | |
shopping_cart = Cart.new | |
shopping_cart.add(ipad, 2) | |
shopping_cart.add(imac, 1) | |
shopping_cart.add(macbook, 1) | |
puts shopping_cart.total # => 3996 | |
html_output = File.new("order_summary.html","w") | |
html_output.puts "<html>" | |
html_output.puts "<head>" | |
html_output.puts "<title>Stuff you bought</title>" | |
html_output.puts "<style>" | |
html_output.puts "h1{color:red}" | |
html_output.puts "</style>" | |
html_output.puts "</head>" | |
html_output.puts "<body>" | |
html_output.puts "<h1>test</h1>" | |
html_output.puts "</body>" | |
html_output.puts "</html>" | |
html_output.close |
Remember that puts is not the same as return. Your total should be returning a value that you will then use to output to your html file.
Thanks gents!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why is your total doing a puts (line 42), then you puts it again on line 59?