Ruby购物车

时间:2016-11-02 04:24:18

标签: ruby

我是Ruby的新手,我很难完成这个购物车计划。我不确定我做错了什么。任何人都可以告诉我如何让最后两行输出我在旁边的评论中的代码?任何帮助,将不胜感激。谢谢。

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>'   

1 个答案:

答案 0 :(得分:0)

麻烦是store.add_to_cart "Pie"中的大写字母。这会将字符串"Pie"添加到您的@cart数组中。当您使用@cart迭代#inject时,@products["Pie"]会返回nil,因为您的哈希中没有"Pie"的密钥(密钥区分大小写) 。您无法将nil添加到sum,这是一个浮点数。

再次尝试使用小写的“馅饼”,它应该可以正常工作。或者,为避免将来出现大写问题,请将cart_total方法更改为@cart.inject(0){ |sum, item| sum + @products[item.downcase] }