【问题标题】:Ruby easy search for key-value pair in an array of hashesRuby 轻松搜索散列数组中的键值对
【发布时间】:2012-05-14 13:31:22
【问题描述】:

假设我有这个哈希数组:

[
{"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 中有没有简单的方法来做到这一点?

【问题讨论】:

  • 编辑了这个问题,因为它与 JSON 没有任何关系。

标签: ruby arrays


【解决方案1】:
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"

【讨论】:

  • 完美!不知道 .find 是一种可以调用的方法。真的很有帮助。
  • @BrianW:Ruby 编程规则#1:学习Enumerable 的方法。然后,再次学习它们。
  • nitpick:find/detect + get 具有不匹配 + 繁荣的典型问题。因此,在没有内置列表理解的 Ruby 中,我会在使用 ick 时写:ary.detect { |h| h['product'] == 'bcx' }.maybe['href']。使用构面时:ary.map_detect { |h| h["href"] if h['product'] == 'bcx' }
  • @tokland:当然,这仅在元素存在时才有效。这是我的一个假设,我没有明确说明,谢谢指出。
猜你喜欢
  • 2011-01-15
  • 2012-03-07
  • 2012-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多