错误:没有将String隐式转换为Integer

时间:2013-11-22 03:12:59

标签: ruby string methods hash integer

任何人都可以告诉我为什么我收到以下代码的错误?

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)

1 个答案:

答案 0 :(得分: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)