通过使用嵌套数组迭代哈希来构建哈希

时间:2015-10-07 03:22:40

标签: ruby hash

我想构建一个从Instagram API调用中获取数据的数据:

{"attribution"=>nil,
 "tags"=>["loudmouth"],
 "location"=>{"latitude"=>40.7181015, "name"=>"Fontanas Bar", "longitude"=>-73.9922791, "id"=>31443955},
 "comments"=>{"count"=>0, "data"=>[]},
 "filter"=>"Normal",
 "created_time"=>"1444181565",
 "link"=>"https://instagram.com/p/8hJ-UwIDyC/",
 "likes"=>{"count"=>0, "data"=>[]},
 "images"=>
  {"low_resolution"=>{"url"=>"https://scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/s320x320/e35/12145134_169501263391761_636095824_n.jpg", "width"=>320, "height"=>320},
   "thumbnail"=>
    {"url"=>"https://scontent.cdninstagram.com/hphotos-xfa1/t51.2885-15/s150x150/e35/c135.0.810.810/12093266_813307028768465_178038954_n.jpg", "width"=>150, "height"=>150},
   "standard_resolution"=>
    {"url"=>"https://scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/s640x640/sh0.08/e35/12145134_169501263391761_636095824_n.jpg", "width"=>640, "height"=>640}},
 "users_in_photo"=>
  [{"position"=>{"y"=>0.636888889, "x"=>0.398666667},
    "user"=>
     {"username"=>"ambersmelson",
      "profile_picture"=>"http://photos-h.ak.instagram.com/hphotos-ak-xfa1/t51.2885-19/11909108_1492226137759631_1159527917_a.jpg",
      "id"=>"194780705",
      "full_name"=>""}}],
 "caption"=>
  {"created_time"=>"1444181565",
   "text"=>"the INCOMPARABLE Amber Nelson closing us out! #loudmouth",
   "from"=>
    {"username"=>"alex3nglish",
     "profile_picture"=>"http://photos-f.ak.instagram.com/hphotos-ak-xaf1/t51.2885-19/s150x150/11906214_483262888501413_294704768_a.jpg",
     "id"=>"30822062",
     "full_name"=>"Alex English"}}

我想以这种方式构建它:

    hash ={}
    hash {"item1"=>
:location => {"latitude"=>40.7181015, "name"=>"Fontanas Bar",      "longitude"=>-73.9922791, "id"=>31443955},
          :created_time => "1444181565",
          :images =>https://scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/s320x320/e35/12145134_169501263391761_636095824_n.jpg"
          :user =>"Alex English"}

我迭代了超过20个对象,每个对象都有它们的位置,图像等...我怎样才能得到像上面那样的哈希结构?

这是我尝试过的:

array_images = Array.new
    # iterate through response object to extract what is needed

     response.each do |item|
        array_images << { :image => item.images.low_resolution.url,
            :location =>  item.location,:created_time => Time.at(item.created_time.to_i), :user => item.user.full_name}

     end

哪个工作正常。那么最好的方法是什么,最快的方式呢?

1 个答案:

答案 0 :(得分:1)

你给出的哈希是数组中的一个项目,存储在一个更大的哈希中的密钥“data”中吗?至少这是标签/端点的方式,所以我假设它在这里是一样的。 (我指的是哈希数组作为数据)

hash = {}
data.each_with_index do |h, idx|
  hash["item#{idx + 1}"] = {
    location: h["location"], #This grabs the entire hash at "location" because you are wanting all of that data
    created_time: h["created_time"],
    image: h["images"]["low_resolution"]["url"], # You can replace this with whichever resolution.
    caption: h["caption"]["from"]["full_name"]
  }
end

我觉得你想要一个更简单的解决方案,但是我不确定这是怎么回事,因为你希望嵌套在不同层次的东西,你从不同层次的嵌套中提取东西。