[ {:upc=>"51857195821952", :product_id=>"1234", :name=>"name", :price=>" $1-6ren">
gpt4 book ai didi

ruby-on-rails - Ruby - "can' t 将符号转换为整数“当尝试访问数组中的数据时

转载 作者:数据小太阳 更新时间:2023-10-29 08:39:12 24 4
gpt4 key购买 nike

这是一个数组示例:

{"C1"=>[
{:upc=>"51857195821952", :product_id=>"1234", :name=>"name", :price=>" $15 ", :color=>"green", :size=>"L", :description=>"descr"},
{:upc=>"352353wegs", :product_id=>"456", :name=>"name2", :price=>"$21", :color=>"black", :size=>"S", :description=>"descr"}, # ...
],
#...
}

在这里,当我试图从该数组中获取数据时:

@array.each do |p|
product = Product.new
product.sku = p[0]
product.name = p[1][0][:name] #can't convert Symbol into Integer
price = p[1].select{ |pr| !pr[:price].nil? and pr[:price] != "0" }.min_by{ |i| i[:price].to_f }[:price]
product.price = "%.2f" % (price.to_f)
...
end

每次我尝试从数组中获取数据时,我都会在 product.name = 行遇到错误无法将 Symbol 转换为 Integer

这种情况有什么问题?我在这个问题上花了一个下午的时间,但不幸的是我仍然无法弄清楚......

谢谢你

最佳答案

您的@array 实际上是一个散列。它的格式如下:

{ 
'name1' => [{:upc => "..."},{:upc => "..."}],
'name2' => [{:upc => "..."},{:upc => "..."}],
#...
}

因为它是一个 Hash,你可以在 each(也适用于 map)方法中使用 2 个参数(一个用于键,另一个用于值) :

@array.each do |name, array|
product = Product.new
product.sku = name # returns "C1"
array.each do |data|
data[:upc]
data[:name]
#etc...
end
end

关于ruby-on-rails - Ruby - "can' t 将符号转换为整数“当尝试访问数组中的数据时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15122559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com