2013-05-07 154 views
0

因此作爲我的previous question的擴展。我發現了這個問題。返回的值的一個散列,但它是一個非常深的散列。因此,這裏的什麼方法打印:所以基本上這是Ruby訪問深度哈希

{"kind"=>"Listing", "data"=>{"modhash"=>"5g8l2yr5ld67bcab9972a4fbf072381e422fea31c6ebf45cb5", "children"=>[{"kind"=>"t3", "data"=>{"domain"=>"i.imgur.com", "banned_by"=>nil, "media_embed"=>{}, "subreddit"=>"pics", "selftext_html"=>nil, "selftext"=>"", "likes"=>nil, "link_flair_text"=>nil, "id"=>"1dtlho", "clicked"=>false, "title"=>"It almost looks like they're holding up a photograph", "media"=>nil, "score"=>3866, "approved_by"=>nil, "over_18"=>false, "hidden"=>false, "thumbnail"=>" http://f.thumbs.redditmedia.com/m2l6DYE1-gSVgpFk.jpg ", "subreddit_id"=>"t5_2qh0u", "edited"=>false, "link_flair_css_class"=>nil, "author_flair_css_class"=>nil, "downs"=>10684, "saved"=>false, "is_self"=>false, "permalink"=>"/r/pics/comments/1dtlho/it_almost_looks_like_theyre_holding_up_a/", "name"=>"t3_1dtlho", "created"=>1367907910.0, "url"=>" http://i.imgur.com/M9BVP7W.jpg ", "author_flair_text"=>nil, "author"=>"kosen13", "created_utc"=>1367879110.0, "ups"=>14550, "num_comments"=>308, "num_reports"=>nil, "distinguished"=>nil}},

我怎麼嘗試訪問它:

@reddit.get_listing().fetch('data',{}).fetch('children',{}).each do |child| 
    puts child['data'] 
end 

使打印:

{"domain"=>"i.imgur.com", "banned_by"=>nil, "media_embed"=>{}, "subreddit"=>"pics", "selftext_html"=>nil, "selftext"=>"", "likes"=>nil, "link_flair_text"=>nil, "id"=>"1dtlho", "clicked"=>false, "title"=>"It almost looks like they're holding up a photograph", "media"=>nil, "score"=>3866, "approved_by"=>nil, "over_18"=>false, "hidden"=>false, "thumbnail"=>" http://f.thumbs.redditmedia.com/m2l6DYE1-gSVgpFk.jpg ", "subreddit_id"=>"t5_2qh0u", "edited"=>false, "link_flair_css_class"=>nil, "author_flair_css_class"=>nil, "downs"=>10684, "saved"=>false, "is_self"=>false, "permalink"=>"/r/pics/comments/1dtlho/it_almost_looks_like_theyre_holding_up_a/", "name"=>"t3_1dtlho", "created"=>1367907910.0, "url"=>" http://i.imgur.com/M9BVP7W.jpg ", "author_flair_text"=>nil, "author"=>"kosen13", "created_utc"=>1367879110.0, "ups"=>14550, "num_comments"=>308, "num_reports"=>nil, "distinguished"=>nil}},

但現在我需要訪問域名和打印標題,所以我嘗試這樣的事情:

@reddit.get_listing().fetch('data',{}).fetch('children',{}).fetch('data', {}).each do |child| 
    puts child['title'] 
end 

但我得到這個錯誤: :in 'fetch': can't convert String into Integer

任何想法如何獲得散列的最後部分?

+1

我看你的問題已經解決了,不過這裏有一個提示:不要將所有的讀取語句鏈接在一起,而是將它拆分爲多個語句。這樣,如果失敗,錯誤消息將指向實際導致錯誤的行。 (它也使代碼更具可讀性)。 – 2013-05-07 06:31:41

回答

2

您不能在陣列上使用fetch。試試這個:

@reddit.get_listing().fetch('data',{}).fetch('children',{}).each do |child| 
    puts child['data']['title'] 
end 
+0

哇...我真的該死,我試過這個......我必須翻轉數據和標題。這工作,謝謝! – Richard 2013-05-07 01:59:46

+0

@理查德:當然。樂意效勞。 – Linuxios 2013-05-07 02:02:08