Richard
Richard

Reputation: 6126

Ruby Accessing Deep Hashes

So as an extension to my previous question. I found out the problem. The returned value is a hash but it's an extremely deep hash. So here's what the method prints:

{"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"=>"https://i.sstatic.net/ycMoe.jpg", "author_flair_text"=>nil, "author"=>"kosen13", "created_utc"=>1367879110.0, "ups"=>14550, "num_comments"=>308, "num_reports"=>nil, "distinguished"=>nil}},

So basically this is how I try to access it:

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

So that prints:

{"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"=>"https://i.sstatic.net/ycMoe.jpg", "author_flair_text"=>nil, "author"=>"kosen13", "created_utc"=>1367879110.0, "ups"=>14550, "num_comments"=>308, "num_reports"=>nil, "distinguished"=>nil}},

But now I need to access the domain and print titles so I tried something like this:

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

But I get this error: :in 'fetch': can't convert String into Integer

Any ideas how to get the last part of the hash?

Upvotes: 0

Views: 179

Answers (1)

Linuxios
Linuxios

Reputation: 35788

You can't use fetch on an array. Try this:

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

Upvotes: 2

Related Questions