Ruby 在散列数组中轻松搜索键值对
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10584326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby easy search for key-value pair in an array of hashes
提问by Brian Weinreich
Suppose I have this array of hashes:
假设我有这个哈希数组:
[
{"href"=>"https://company.campfirenow.com", "name"=>"Company", "id"=>123456789, "product"=>"campfire"},
{"href"=>"https://basecamp.com/123456789/api/v1", "name"=>"Company", "id"=>123456789, "product"=>"bcx"},
{"href"=>"https://company.highrisehq.com", "name"=>"Company", "id"=>123456789, "product"=>"highrise"}
]
How can I parse the "href" value of the hash where "product"=>"bcx"
如何解析散列的“ href”值,其中“product”=>“bcx”
Is there any easy way to do this in Ruby?
有没有什么简单的方法可以在 Ruby 中做到这一点?
回答by Niklas B.
ary = [
{"href"=>"https://company.campfirenow.com", "name"=>"Company", "id"=>123456789, "product"=>"campfire"},
{"href"=>"https://basecamp.com/123456789/api/v1", "name"=>"Company", "id"=>123456789, "product"=>"bcx"},
{"href"=>"https://company.highrisehq.com", "name"=>"Company", "id"=>123456789, "product"=>"highrise"}
]
p ary.find { |h| h['product'] == 'bcx' }['href']
# => "https://basecamp.com/123456789/api/v1"
Note that this only works if the element exists. Otherwise you will be calling the subscription operator []on nil, which will raise an exception, so you might want to check for that first:
请注意,这仅在元素存在时才有效。否则,您将调用订阅运算符[]on nil,这将引发异常,因此您可能需要先检查:
if h = ary.find { |h| h['product'] == 'bcx' }
p h['href']
else
puts 'Not found!'
end
If you need to perform that operation multiple times, you should build yourself a data structure for faster lookup:
如果您需要多次执行该操作,您应该为自己构建一个数据结构以加快查找速度:
href_by_product = Hash[ary.map { |h| h.values_at('product', 'href') }]
p href_by_product['campfire'] # => "https://company.campfirenow.com"
p href_by_product['bcx'] # => "https://basecamp.com/123456789/api/v1"

