不太确定如何将其作为标题质疑...
但这是情况和问题:
我从API获取订单。接受订单时,我想根据产品的重量添加运费。我使用图章中的API来接收费率,我想从图章API响应中收取最便宜的费率。
这是我尝试获取费率的方法(该费率可在前端显示,但在以下显示时不起作用)。...
...
rates = Shipstation::Shipment.get_rates({...})
cheapest_rate = rates.min_by { |rate| rate['shipmentCost'] }
cheapest_rate_number = cheapest_rate["shipmentCost"]
错误:
TypeError (no implicit conversion of String into Integer) on line 75
第75行:cheapest_rate = rates.min_by { |rate| rate['shipmentCost'] }
目标是获取最低的可用数字,将其用于@order.shipping_rate
,然后再用于计算处理的总付款。
@rates
JSON响应如下:
[{"serviceName"=>"USPS First Class Mail - Package", "serviceCode"=>"usps_first_class_mail", "shipmentCost"=>2.66, "otherCost"=>0.0}, {"serviceName"=>"USPS Priority Mail - Package", "serviceCode"=>"usps_priority_mail", "shipmentCost"=>6.95, "otherCost"=>0.0}]
但有多个选项。
我如何使用当前代码和/或新代码从\"shipmentCost\"
获取最低整数,对其进行定义,然后将其传递给模型,而不会出现来自上方的错误>
答案 0 :(得分:0)
[{“ serviceName” =>“ USPS First Class Mail-Package”,“ serviceCode” =>“ usps_first_class_mail”,“ shipmentCost” => 2.66,“ otherCost” => 0.0},{“ serviceName” =>“ USPS优先邮件-包裹“,” serviceCode“ =>” usps_priority_mail“,” shipmentCost“ => 6.95,” otherCost“ => 0.0}]
通过此哈希数组,您可以简单地执行以下操作:
rates = Shipstation::Shipment.get_rates({...})
cheapest_rate_number = rates.collect { |h| h["shipmentCost"].to_f }.min
您发布的错误提示并非所有"shipmentCost"
值都是整数或浮点数,因此即使某些值是整数/浮点数而有些是字符串,我们也只是将它们转换为浮点数以确保安全。