如果值存在,则显示哈希的内容

时间:2018-05-22 07:03:01

标签: ruby hash

我有一个哈希:

req = {
  "count" => 50100,
  "results" => [
    {"listing_id" => 615929315, "state" => "active", "user_id" => 140604756, "category_id" => 69150367}, 
    {"listing_id" => 615929311, "state" => "active", "user_id" => 152528025, "category_id" => 69150367}
  ]
}

如果存在特定的user_id,我想查找并显示整个内部哈希值。我能找到它:

req["results"][0].select{|key, value| value == 152528025}
# => {"user_id" => 152528025}

如何显示整个(嵌套)哈希?

{"listing_id" => 615929311, "state" => "active", "user_id" => 152528025, "category_id" => 69150367}

1 个答案:

答案 0 :(得分:4)

req["results"].select{|x| x["user_id"] == 152528025}