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"

注意!

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



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