访问哈希数组中的每个密钥

时间:2018-12-27 14:20:58

标签: ruby

我有以下一系列的哈希值。

[{"comments_count"=>3, "like_count"=>341, "media_type"=>"IMAGE", "media_url"=>"https://url1.jpg", "permalink"=>"https://www.url.com", "timestamp"=>"2018-09-16T11:29:09+0000", "id"=>"17881817992270180"}, {"comments_count"=>1, "like_count"=>209, "media_type"=>"IMAGE", "media_url"=>"https://url2.jpg", "permalink"=>"https://www.url2.com", "timestamp"=>"2018-09-15T18:38:59+0000", "id"=>"17950602214183642"}]

我想像这样遍历每个media_url

Array.each do |media|
    media.media_url
end

但是出现以下错误:

undefined method `media_url' for Hash:0x00007fb987684d48

2 个答案:

答案 0 :(得分:4)

使用[]访问哈希值-不是JS:)

a = [{"comments_count"=>3, "like_count"=>341, "media_type"=>"IMAGE", "media_url"=>"https://url1.jpg", "permalink"=>"https://www.url.com", "timestamp"=>"2018-09-16T11:29:09+0000", "id"=>"17881817992270180"}, {"comments_count"=>1, "like_count"=>209, "media_type"=>"IMAGE", "media_url"=>"https://url2.jpg", "permalink"=>"https://www.url2.com", "timestamp"=>"2018-09-15T18:38:59+0000", "id"=>"17950602214183642"}]
a.each {|h| h['media_url']  }

答案 1 :(得分:2)

或者,您可以通过使用Hash上的.fetch()方法来引用特定键的值。

arr = [{"comments_count"=>3, "like_count"=>341, "media_type"=>"IMAGE", "media_url"=>"https://url1.jpg", "permalink"=>"https://www.url.com", "timestamp"=>"2018-09-16T11:29:09+0000", "id"=>"17881817992270180"}, {"comments_count"=>1, "like_count"=>209, "media_type"=>"IMAGE", "media_url"=>"https://url2.jpg", "permalink"=>"https://www.url2.com", "timestamp"=>"2018-09-15T18:38:59+0000", "id"=>"17950602214183642"}]

arr.each {|h| h.fetch('media_url') }

如果在某些哈希中未找到密钥,则可以指定默认值:

arr.each {|h| h.fetch('media_url') { 'https://default_url.jpg' } } 

要直接以链接数组形式返回输出,只需使用.map()即可:

arr.map {|h| h.fetch('media_url') { nil } }