【问题标题】:Error: no implicit conversion of String into Integer错误:没有将字符串隐式转换为整数
【发布时间】:2023-09-03 21:45:01
【问题描述】:

谁能告诉我为什么我收到以下代码的此错误?

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)

【问题讨论】:

  • 您是否正确转录代码?如图所示,此代码应在分配给single_order_totals[coffee_sku]['cost_to_customer'] 的行上生成错误Undefined method [] for nil?请显示确切的错误并识别堆栈跟踪顶部的行。
  • 谢谢彼得。在进行错字更正以使其正常工作后,我必须像这样初始化:single_order_totals = Hash.new { |hash, key|哈希[键] = [] }

标签: ruby string methods hash integer


【解决方案1】:

除了上面评论中提到的问题之外,您在第 5 行和第 6 行有错字。

coffee_info_hash['num_bags]']

应该是这样的

coffee_info_hash['num_bags']

此外,single_order_totals[coffee_sku] 的计算结果为零,因为 single_order_totalsHash.new(0) 中使用默认值零初始化。

你得到的错误似乎来自

coffee_info_hash["RetailPrice"]

大概所有的 SKU 都是整数。因此,您实际上是在尝试在此处访问整数上的“RetailPrice”。

一个类似的例子:

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

【讨论】:

  • 谢谢@jmromer。我进行了类型更改,还发现我需要初始化 single_order_totals = Hash.new { |hash, key| hash[key] = [] } 以使其其余部分正常工作
最近更新 更多