【发布时间】:2016-11-02 12:42:01
【问题描述】:
我是 Ruby 的新手,我在完成这个购物车程序时遇到了困难。我不确定我做错了什么。谁能告诉我如何让最后两行输出我在他们旁边的 cmets 中的代码?任何帮助,将不胜感激。谢谢。
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
当我尝试运行它时,我得到了这个错误:
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>'
【问题讨论】:
-
检查
pie的大小写;-) -
请记住浮点值始终是近似值,因此将它们用于货币计算很麻烦。
标签: ruby