0

所以作为我之前问题的延伸。我发现了问题。返回的值一个散列,但它是一个非常深的散列。所以这是该方法打印的内容:

{"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"=>"看起来他们好像举着一张照片", "media "=>nil, "score"=>3866, "approved_by"=>nil, "over_18"=>false, "hidden"=>假,“缩略图”=>“ 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,“永久链接”=>“/r/pics/comments/1dtlho/it_almost_looks_like_theyre_holding_up_a/”,“名称”=>“t3_1dtlho”,“创建”=>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, “杰出”=>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"=>"看起来他们好像举着一张照片", "媒体"=>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"=>无,“author_flair_css_class”=>无,“downs”=>10684,“保存”=>false,“is_self”=>false,“永久链接”=>“/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"= >无}},

但现在我需要访问域并打印标题,所以我尝试了这样的事情:

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

但我得到这个错误: :in 'fetch': can't convert String into Integer

任何想法如何获得哈希的最后一部分?

4

1 回答 1

2

您不能fetch在数组上使用。尝试这个:

@reddit.get_listing().fetch('data',{}).fetch('children',{}).each do |child|
    puts child['data']['title']
end
于 2013-05-07T01:55:00.947 回答