如何查找包含具有值数组的哈希的匹配值的哈希键

时间:2014-12-23 07:09:57

标签: ruby-on-rails ruby arrays hash

我有这样的情况:

clients = {
"yellow"=>[{"client_id"=>"2178","price" => 1},{"client_id" => "2282","price" => 2}], 
"orange"=>[{"client_id"=>"2180","price" => 1},{"client_id" => "2283","price" => 3}],
"red"=>[{"client_id"=>"2178","price" => 1},{"client_id" => "2282","price" => 3}],
"blue"=>[{"client_id"=>"2180","price" => 1},{"client_id" => "2283","price" => 1}]
 }

我需要获取客户端ID =>的密钥。 [2282,2178]并根据价格获得最低的关键值。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

res = []
client.each{|k, v|
 res << k if  v.detect{|hash| hash["client_id"] == "2282"}
}
res
#=> ["red", "yellow"]

注意 这个答案适用于OP原始问题,需要找到包含&#34; client_id&#34;我没有更新我的答案,因为OP非常懒惰地改变了要求。