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"
请注意,这仅在元素存在时才有效。否则,您将调用订阅运算符[]
on nil
,这将引发异常,因此您可能需要先检查一下:
if h = ary.find { |h| h['product'] == 'bcx' }
p h['href']
else
puts 'Not found!'
end
如果您需要多次执行该操作,您应该为自己构建一个数据结构以便更快地查找:
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"