Ruby访问深度哈希

时间:2013-05-07 01:51:58

标签: ruby parsing hash

作为previous question的扩展名。我发现了问题。返回值哈希值,但它是一个非常深的哈希值。所以这是方法打印的内容:

  

{ “种类”=> “中列表”,   “数据”=> { “modhash”=> “中5g8l2yr5ld67bcab9972a4fbf072381e422fea31c6ebf45cb5”,   “children”=> [{“kind”=>“t3”,“data”=> {“domain”=>“i.imgur.com”,   “banned_by”=> nil,“media_embed”=> {},“subreddit”=>“pics”,   “selftext_html”=> nil,“selftext”=>“”,“赞”=> nil,   “link_flair_text”=> nil,“id”=>“1dtlho”,“clicked”=> false,“title”=>“它   几乎看起来他们正拿着一张照片“,”媒体“=  nil,   “score”=> 3866,“approved_by”=> nil,“over_18”=> false,“hidden”=> false,   “缩略图”=> “中http://f.thumbs.redditmedia.com/m2l6DYE1-gSVgpFk.jpg”,   “subreddit_id”=>“t5_2qh0u”,“编辑”=> 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

所以打印:

  

{ “结构域”=> “中i.imgur.com”,   “banned_by”=> nil,“media_embed”=> {},“subreddit”=>“pics”,   “selftext_html”=> nil,“selftext”=>“”,“赞”=> nil,   “link_flair_text”=> nil,“id”=>“1dtlho”,“clicked”=> false,“title”=>“它   几乎看起来他们正拿着一张照片“,”媒体“=  nil,   “score”=> 3866,“approved_by”=> nil,“over_18”=> false,“hidden”=> false,   “缩略图”=> “中http://f.thumbs.redditmedia.com/m2l6DYE1-gSVgpFk.jpg”,   “subreddit_id”=>“t5_2qh0u”,“编辑”=> 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 个答案:

答案 0 :(得分:2)

您无法在阵列上使用fetch。试试这个:

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