在散列哈希中搜索并返回键

时间:2016-01-06 14:16:33

标签: ruby

我有以下哈希:

{1=>{"label"=>"New", "color"=>"#whatver"}, 2=>{"label"=>"In-progress", "color"=>"#whatever"}, 3=>{"label"=>"Closed", "color"=>"#whatever"}}

我有一个像['New', 'In-progress']

这样的数组

我需要从该哈希中返回数组中的键[1, 2]

我做了什么尝试:

labels = ['New', 'In-progress']
labels.map { |label| statuses.detect { |hash| hash.second[:label] == label }.first }
# => [1, 2]

哪个是正确的,我想要的确切,但有更直接的方法吗?

4 个答案:

答案 0 :(得分:2)

就你想要达到的目标而言,可能不会那么短但更清晰:

h.select { |_, value| ['New', 'In-progress'].include?(value['label']) }.keys

答案 1 :(得分:2)

h = {1=>{"label"=>"New", "color"=>"#whatver"},
     2=>{"label"=>"In-progress", "color"=>"#whatever"},
     3=>{"label"=>"Closed", "color"=>"#whatever"}}
labels = ['New', 'In-progress']

h.select { |_,v| (v.values & labels).any? }.keys
  #=> [1, 2] 

答案 2 :(得分:0)

除了@ndn的回答之外,还有两种方法可以提取所需的密钥。

data = {1=>{"label"=>"New", "color"=>"#whatver"}, 2=>{"label"=>"In-progress", "color"=>"#whatever"}, 3=>{"label"=>"Closed", "color"=>"#whatever"}}

labels = ['New', 'In-progress']

data.map{|k, h| k if labels.include?(h["label"])}.compact
# => [1, 2]

data.dup.delete_if{|_, h| !labels.include?(h["label"])}.keys
# => [1, 2]

答案 3 :(得分:0)

您可以执行以下操作:

h = {1=>{"label"=>"New", "color"=>"#whatver"}, 
   2=>{"label"=>"In-progress", "color"=>"#whatever"}, 
   3=>{"label"=>"Closed", "color"=>"#whatever"}}

labels = ['New', 'In-progress']

result = h.select do |k, hash|
    # Check if any label is part of values array
    labels.any? {|label| hash.values.include?(label)}
end

p result.keys
#=> [1,2]