2013-11-22 63 views
-1

誰能告訴我爲什麼我在下面的代碼中收到此錯誤?錯誤:沒有將字符串隱式轉換爲整數

def total_single_order(one_order) 
    single_order_totals = Hash.new(0) 
    one_order.each do |coffee_sku, coffee_info_hash| 
    binding.pry 
    single_order_totals[coffee_sku]['cost_to_customer'] = (coffee_info_hash["RetailPrice"].to_f * coffee_info_hash['num_bags]'].to_f) 
    single_order_totals[coffee_sku]['cost_to_company'] = (coffee_info_hash["PurchasingPrice"].to_f * coffee_info_hash['num_bags]'].to_f) 
    end 
    single_order_totals 
end 

total_single_order(one_order) 
+0

你正確抄寫的代碼?如圖所示,該代碼應生成一個錯誤'未定義方法[]爲上線nil'指派到'single_order_totals [coffee_sku] [「cost_to_customer」]'?請顯示確切的錯誤,標識堆棧跟蹤頂部的行。 –

+0

謝謝彼得。爲了得到這個工作,我使用了錯誤修正後的初始化方式,如下所示:single_order_totals = Hash.new {| hash,key | hash [key] = []} – John

回答

1

除了上面評論中提到的問題之外,您在第5行和第6行有錯字。

coffee_info_hash['num_bags]'] 

看起來應該是

coffee_info_hash['num_bags'] 

此外,single_order_totals[coffee_sku]計算結果爲零,因爲single_order_totals與在Hash.new(0)的默認值爲零初始化。

你得到的錯誤似乎來自

coffee_info_hash["RetailPrice"] 

想必所有的SKU整數到來。所以你實際上試圖在這裏訪問一個整數的'RetailPrice'。

一個類似的例子:

sku = 45 
sku["key"] 
#=> in `[]': no implicit conversion of String into Integer (TypeError) 
+1

謝謝@jmromer。我做了類型更改,並且還發現我需要初始化single_order_totals = Hash.new {| hash,key | hash [key] = []},以便讓其餘部分工作 – John

相關問題