Ruby可以轻松搜索散列数组中的键值对

[英]Ruby easy search for key-value pair in an array of hashes


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中有没有简单的方法呢?

1 个解决方案

#1


49  

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:

请注意,这仅在元素存在时才有效。否则,您将在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"
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2012/05/14/7203a3bfe61c473682a9e9db5b889f8e.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告