【问题标题】:Ruby Shopping Cart红宝石购物车
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-26
    • 2017-11-18
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    相关资源
    最近更新 更多