2016-11-02 14 views
0

Rubyで新しく、このショッピングカートプログラムを終了するのが難しいです。私は何が間違っているのか分かりません。誰も私の隣にあるコメントのコードを出力する最後の2行を取得する方法を教えてもらえますか?どんな助けもありがとう。ありがとう。私はこれを実行しようとすると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>' 
+0

'pie'の大文字を確認してください;-) – Carpetsmoker

+0

浮動小数点の値は常に近似値なので、貨幣の計算には問題があります。 – tadman

答えて

0

トラブルがstore.add_to_cart "Pie"で大文字の文字です。これにより、文字列"Pie"@cart配列に追加されます。 を使用して@cartを反復処理すると、"Pie"のキーが存在しないため、@products["Pie"]nilを返します(キーでは大文字と小文字が区別されます)。 floatであるsumnilを追加することはできません。

小文字の「パイ」でもう一度お試しください。正常に動作するはずです。または今後大文字の問題を回避するには、cart_totalメソッドを@cart.inject(0){ |sum, item| sum + @products[item.downcase] }に変更してください。