使用“AND”操作从ruby中的哈希数组中选择哈希值

时间:2016-09-08 20:42:46

标签: arrays ruby select hash include

input = [ {"name" => "adam",  "nick" => ["kuruvi", "cali"] },
          {"name" => "eve",   "nick" => ["cali"]           },
          {"name" => "enoch", "nick" => []                 },    
          {"name" => "ebe",   "nick" => ["test", "wrong"]  },
          {"name" => "fred",  "nick" => ["da"]             } ]

我想选择包含"da"&的哈希值"cali"中的"nick"

input.select do |d|
  d["nick"].include?("cali")
end

给出

[{"name"=>"adam", "nick"=>["kuruvi", "cali"]},
 {"name"=>"eve", "nick"=>["cali"]}]

我们如何检查两个参数。例如:include?("cali","da")以便我的结果

 [{"name"=>"adam", "nick"=>["kuruvi", "cali"]},
  {"name"=>"eve", "nick"=>["cali"]},
  {"name" => "fred",  "nick" => ["da"]}]

试过这个

 i = ["da","cali"]
 input.select do |d|
   d["nick"].all? { |v| i.include? v }
 end

=> [{"name" => "adam",  "nick" => ["kuruvi", "cali"]},
    {"name" => "eve",   "nick" => ["cali"]},
    {"name" => "enoch", "nick" => []},
    {"name" => "fred",  "nick" => ["da"]}]

(但这会返回带"nick"=[]的哈希值)

3 个答案:

答案 0 :(得分:2)

根据您想要的结果,您指的是"或",而不是"和"。以下使用方法Array#&

input.reject { |h| (h["nick"] & ["cali", "da"]).empty? }
  #=> [{"name"=>"adam", "nick"=>["kuruvi", "cali"]},
  #    {"name"=>"eve", "nick"=>["cali"]},
  #    {"name"=>"fred", "nick"=>["da"]}] 

答案 1 :(得分:1)

您需要进行两项不同的include?测试:

l = d['nick']
l.include?('da') && l.include?('cali')

您也可以尝试:

(d['nick'] & %w[ da cali ]).length == 2

或者,如果你想要,你可以编写自己的方法来测试重叠,或者甚至将它修补为数组include_all?

答案 2 :(得分:0)

您可以使用all?来获得所需的结果,而不是使用any?

input.select do |d|
  d["nick"].any? { |h| ['cali','da'].include?(h) }
end

返回

[{"name"=>"adam", "nick"=>["kuruvi", "cali"]}, 
 {"name"=>"eve",  "nick"=>["cali"]}, 
 {"name"=>"fred", "nick"=>["da"]}]