use*_*621 3 ruby arrays integer symbols ruby-on-rails
这是一个数组示例:
{"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"}, # ...
],
#...
}
Run Code Online (Sandbox Code Playgroud)
在这里,当我试图从该数组中获取数据时:
@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
Run Code Online (Sandbox Code Playgroud)
每次我尝试从数组中获取数据时,我都会遇到product.name =错误无法将 Symbol 转换为 Integer。
在这种情况下有什么问题?我在这个问题上花了一个下午的时间,但不幸的是我仍然无法弄清楚......
谢谢你
你@array实际上是一个哈希。它的格式如下:
{
'name1' => [{:upc => "..."},{:upc => "..."}],
'name2' => [{:upc => "..."},{:upc => "..."}],
#...
}
Run Code Online (Sandbox Code Playgroud)
由于它是一个哈希,您可以在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
Run Code Online (Sandbox Code Playgroud)