如何找到包含匹配值的哈希键
问题描述:
鉴于我有以下 clients 哈希,是否有一种快速的 ruby 方式(无需编写多行脚本)来获取给定我想要匹配 client_id 的密钥?例如.如何获取client_id == "2180"
的密钥?
Given I have the below clients hash, is there a quick ruby way (without having to write a multi-line script) to obtain the key given I want to match the client_id? E.g. How to get the key for client_id == "2180"
?
clients = {
"yellow"=>{"client_id"=>"2178"},
"orange"=>{"client_id"=>"2180"},
"red"=>{"client_id"=>"2179"},
"blue"=>{"client_id"=>"2181"}
}
答
你可以使用 Enumerable#select:
clients.select{|key, hash| hash["client_id"] == "2180" }
#=> [["orange", {"client_id"=>"2180"}]]
请注意,结果将是所有匹配值的数组,其中每个值都是键和值的数组.
Note that the result will be an array of all the matching values, where each is an array of the key and value.