嵌套哈希中的对象取决于键值

时间:2015-03-12 19:52:44

标签: ruby

我收到了谷歌API回应,并有以下哈希:

api_response = {"0"=>{"id"=>"xxx.id.google.com^xxx", "hasMicrophone"=>"true", "hasCamera"=>"true", "hasAppEnabled"=>"false", "isBroadcaster"=>"false", "isInBroadcast"=>"true", "displayIndex"=>"0", "person"=>{"id"=>"xxx", "displayName"=>"Foo Bar", "image"=>{"url"=>".../s96-c/photo.jpg"}, "fa"=>"false"}, "locale"=>"en", "fa"=>"false"}, "1"=>{"id"=>"xxx.id.google.com^3772edb7c0", "hasMicrophone"=>"true", "hasCamera"=>"true", "hasAppEnabled"=>"false", "isBroadcaster"=>"false", "isInBroadcast"=>"true", "displayIndex"=>"1", "person"=>{"id"=>"xxx", "displayName"=>"Bar Foo", "image"=>{"url"=>".../s96-c/photo.jpg"}, "fa"=>"false"}, "locale"=>"en", "fa"=>"false"}, "2"=>{"id"=>"xxx.id.google.com^98ebb1f610", "hasMicrophone"=>"true", "hasCamera"=>"true", "hasAppEnabled"=>"true", "isBroadcaster"=>"true", "isInBroadcast"=>"true", "displayIndex"=>"2", "person"=>{"id"=>"xxx", "displayName"=>"John Doe", "image"=>{"url"=>".../s96-c/photo.jpg"}, "fa"=>"false"}, "locale"=>"en", "fa"=>"false"}}

我需要从displayName的嵌套哈希中获取"isBroadcaster"=>"true"的值。 (在这种情况下,displayNameJohn Doe)。我无法理解这个问题并希望得到一些帮助。提前谢谢。

4 个答案:

答案 0 :(得分:4)

假设只有1名广播员。

api_response.each do |_, hash|
  break hash['person']['displayName'] if hash['isBroadcaster'] == 'true'
end

对于多家广播公司,请:

api_response.each_with_object([]) do |(_, hash), array|
  array << hash['person']['displayName'] if hash['isBroadcaster'] == 'true'
end

答案 1 :(得分:2)

你必须做

# get all broadcasters
api_response.map do |_, hash| 
  hash["person"]["displayName"] if hash["isBroadcaster"] == "true"
end.compact
# if you want the first broadcaster, then
broad_caster = api_response.find do |_, hash|
  hash["isBroadcaster"] == "true"
end
broad_caster && broad_caster.last["person"]["displayName"]

答案 2 :(得分:0)

您可以将selectmap结合起来Enumerable以获得第一场比赛。

display_name = api_response.select { |k,v|
  v['isBroadcaster'] == 'true'
}.map { |k,v|
  v['person']['displayName']
}.first

答案 3 :(得分:0)

因为你不关心密钥如何:

broadcaster = api_response.values.detect{|h| h['isBroadcaster'] == 'true'}
broadcaster ? broadcaster['person']['displayName'] : nil

或者这也会起作用:

api_response.values.detect(->{{'person'=>{}}}){|h| h['isBroadcaster'] == 'true'}['person']['displayName']

然后,如果没有,它会找到第一个isBroadcaster或返回nil