sgfp sgfp - 1 month ago 20
Ruby Question

Ruby Shopping Cart

I'm new at Ruby and I'm having difficulty finishing this shopping cart program. I'm not sure what I'm doing wrong. Can anyone tell me how to get the last two lines to output the code that I have in comments next to them? Any help would be appreciated. Thanks.

class Store

def initialize
@products = {"eggs" => 1.5, "bread" => 3.00, "granola cereal" => 3.4, "coffee" => 2.3, "pie" => 4.7}
@cart = []
end

def add_to_cart( item )
@cart << item
end

def add_product( item, price )
@products[item] = price
end

def cart_total
@cart.inject(0){|sum, item| sum + @products[item]}
end

def items
@products.join(', ')
end
end


store = Store.new
store.add_to_cart "eggs"
store.add_to_cart "Pie"
store.add_to_cart "bread"
puts store.cart # output: eggs, pie, bread
printf "$%6.2f", store.cart_total # output: $ 9.20


When I try to run this, I get this error:

nil can't be coerced into Float
(repl):17:in `+'
(repl):17:in `block in total'
(repl):17:in `each'
(repl):17:in `inject'
(repl):17:in `total'
(repl):28:in `<main>main>'

Answer

The trouble is a capitalized letter in store.add_to_cart "Pie". This adds the string "Pie" to your @cart array. When you iterate over @cart using #inject, @products["Pie"] returns nil, because there is no key for "Pie" in your hash (the keys are case-sensitive). You can't add nil to sum, which is a float.

Try again with a lowercase "pie" and it should work fine. Or to avoid capitalization issues in the future, change your cart_total method to @cart.inject(0){ |sum, item| sum + @products[item.downcase] }.