26

假设我有这个哈希数组:

[
{"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"}
]

如何解析“product”=>“bcx”的哈希值的“ href ”值

在 Ruby 中有没有简单的方法来做到这一点?

4

1 回答 1

53
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"
于 2012-05-14T13:33:46.830 回答