【发布时间】: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