在哈希数组的Ruby容易寻找键值对 [英] Ruby easy search for key-value pair in an array of hashes
本文介绍了在哈希数组的Ruby容易寻找键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有此数组哈希的:
[
{的href=>中https://company.campfirenow.com,名= GT;本公司,ID=> 123456789,产品= GT;篝火},
{的href=>中https://basecamp.com/123456789/api/v1,名= GT;本公司,ID=> 123456789,产品= GT;BCX },
{的href=>中https://company.highrisehq.com,名= GT;本公司,ID=> 123456789,产品= gt;中高层}
]
我如何解析的href 的哈希值,其中产品=>BCX
有没有简单的方法在Ruby中做到这一点?
解决方案
元= [
{的href=>中https://company.campfirenow.com,名= GT;本公司,ID=> 123456789,产品= GT;篝火},
{的href=>中https://basecamp.com/123456789/api/v1,名= GT;本公司,ID=> 123456789,产品= GT;BCX },
{的href=>中https://company.highrisehq.com,名= GT;本公司,ID=> 123456789,产品= gt;中高层}
]p {ary.find | H | H ['产品'] =='BCX'} ['href属性]
#=> https://basecamp.com/123456789/api/v1
请注意,如果元素存在,这仅适用。否则,你将被调用认购运营商 []
在无
,这将引发异常,所以你可能要检查,首先:
如果h = {ary.find | H | H ['产品'] =='BCX'}
P H ['href属性]
其他
把不存在!
结束
如果您需要执行该操作多次,你应该建立自己更快的查找数据结构:
href_by_product =哈希[ary.map {| H | h.values_at(产品,HREF')}]
p href_by_product ['篝火']#=> https://company.campfirenow.com
p href_by_product ['BCX']#=> https://basecamp.com/123456789/api/v1
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"
Is there any easy way to do this in Ruby?
解决方案
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:
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"
这篇关于在哈希数组的Ruby容易寻找键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文