在Rails中迭代这个结构的最佳方法是什么?

时间:2014-10-31 08:07:34

标签: ruby-on-rails ruby arrays etsy

我是铁道新手,无法弄清楚如何迭代这些数据。这是集成了etsy API的gem的输出。它看起来像一组哈希,也许?

output=[#<Etsy::Listing:0x5551ba8 @result={"listing_id"=>182661496, "title"=>"Edible Butterflies in Coral", "quantity"=>1, "price"=>"12.50", "ending_tsz"=>1405362199, "shipping_template_id"=>nil, "MainImage"=>{"url_75x75"=>"https://img1.etsystatic.com/036/0/8545731/il_75x75.576542775_ibud.jpg"}}, @token="token", @secret="secret">, 
#<Etsy::Listing:0x5551bc0 @result={"listing_id"=>182671909, "title"=>"Marshmallow Sampler Pack", "quantity"=>3, "price"=>"9.50", "ending_tsz"=>1405362468, "shipping_template_id"=>1680751676, "MainImage"=>{"url_75x75"=>"https://img1.etsystatic.com/021/0/8545731/il_75x75.576544537_n2zo.jpg"}}, @token="token", @secret="secret">, 
#<Etsy::Listing:0x5551bf0 @result={"listing_id"=>182663346, "title"=>"Gourmet popcorn and seasoning kit", "quantity"=>15, "price"=>"26.95", "ending_tsz"=>1405363087, "shipping_template_id"=>nil, "MainImage"=>{"url_75x75"=>"https://img0.etsystatic.com/026/0/8545731/il_75x75.576428850_r1mv.jpg"}}, @token="token", @secret">, 
#<Etsy::Listing:0x5551c08 @result={"listing_id"=>189414412, "title"=>"Sailor Tote Bag", "quantity"=>45, "price"=>"50.00", "ending_tsz"=>1410586221, "shipping_template_id"=>1024284528, "MainImage"=>{"url_75x75"=>"https://img0.etsystatic.com/039/0/8545731/il_75x75.576443100_slse.jpg"}}, @token="token", @secret="secret">]

我尝试的任何东西似乎都没有用。将它作为数组处理适用于某些事情,例如:output.length正确返回 4 。但是输出[0]返回&lt; Etsy :: Listing:0x5483418&gt; ,没有任何其他数据。我实际需要的只是@ result = {}中包含的内容。想法?谢谢!

2 个答案:

答案 0 :(得分:0)

您写道:

  

它看起来像一组哈希,也许?

这是一个对象数组。每个对象都是Etsy::Listing个实例。您应该能够在Rails控制台上执行此操作:

> listing = output.first
#=> <Etsy::Listing:0x5483418>
> listing.result
#=> {"listing_id"=>182661496, …}

如果您想对每个商家信息做一些事情,您可以这样做:

> output.each {|listing| puts listing.result.title }
Edible Butterflies in Coral
Marshmallow Sampler Pack
Gourmet popcorn and seasoning kit
Sailor Tote Bag
> 

答案 1 :(得分:0)

您似乎错过了阅读this in doc

listings = output.map do |listing| 
  { 
    "title"    => listing.title, 
    "quantity" => listing.quantity, 
    "price"    => listing.price
  }
end