Ruby可以轻松搜索哈希数组中的键值对

时间:2012-05-14 13:31:23

标签: ruby arrays

假设我有这个哈希数组:

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

如何解析散列的“ href ”值“product”=>“bcx”

在Ruby中有没有简单的方法呢?

1 个答案:

答案 0 :(得分:50)

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"

请注意,这仅在元素存在时才有效。否则,您将在[]上调用订阅运算符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"