如何根据多个值删除哈希值

时间:2015-06-08 09:10:38

标签: ruby-on-rails ruby hash

我有以下列表:

hash_list = 
{ "a"=>{"unit_id"=>"43", "dep_id"=>"153","_destroy"=>"false"},
  "b"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"1"},
  "c"=>{"unit_id"=>"43", "dep_id"=>"154", "_destroy"=>"false"},
  "d"=>{"unit_id"=>"42", "dep_id"=>"154", "_destroy"=>"false"}
}

我需要结果为:

{
 "a"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false"},
 "b"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"1"},
 "d"=>{"unit_id"=>"42", "dep_id"=>"154", "_destroy"=>"false"}
}

基本上,unit_id不应该重复。但是,所有_destroy=="1"条目都可以显示在列表中。

请帮忙。

3 个答案:

答案 0 :(得分:5)

试试这个:

> hash_list.to_a.uniq{|_,v|v["unit_id"] unless v["_destroy"] == "1"}.to_h

#=> {
      "a"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false"},
      "b"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"1"},
      "d"=>{"unit_id"=>"42", "dep_id"=>"154", "_destroy"=>"false"}
    }

这将检查unit_id为uniq,并且还会显示"_destory" == "1"个条目。

答案 1 :(得分:1)

此代码:

keepers = hash_list.select { |_k, v| v["_destroy"] == "1" }.to_h
new_hash_list = hash_list.to_a.uniq { |_k, v| v["unit_id"] }.to_h
new_hash_list.merge!(keepers)

针对此数据运行时:

hash_list = { 
  "a"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false"},
  "b"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"1"},
  "c"=>{"unit_id"=>"43", "dep_id"=>"154", "_destroy"=>"false"},
  "d"=>{"unit_id"=>"42", "dep_id"=>"154", "_destroy"=>"false"},
  "e"=>{"unit_id"=>"42", "dep_id"=>"154", "_destroy"=>"1"},
}

产生这个结果:

{
  "a"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false"},
  "d"=>{"unit_id"=>"42", "dep_id"=>"154", "_destroy"=>"false"},
  "b"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"1"},
  "e"=>{"unit_id"=>"42", "dep_id"=>"154", "_destroy"=>"1"},
}

答案 2 :(得分:0)

另一种方式:

new_hash_list =
  { "a"=>{ "unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false" },
    "b"=>{ "unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"1"     },
    "c"=>{ "unit_id"=>"43", "dep_id"=>"154", "_destroy"=>"false" },
    "d"=>{ "unit_id"=>"42", "dep_id"=>"154", "_destroy"=>"false" },
    "e"=>{ "unit_id"=>"43", "dep_id"=>"cat", "_destroy"=>"1"     }}

require 'set'

s = Set.new
new_hash_list.each_with_object({}) do |(k,v),h|
  (h[k] = v) if v["_destroy"] == "1" || s.add?(v["unit_id"])
end
  #=> {"a"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false"},
  #    "b"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"1"    },
  #    "d"=>{"unit_id"=>"42", "dep_id"=>"154", "_destroy"=>"false"},
  #    "e"=>{"unit_id"=>"43", "dep_id"=>"cat", "_destroy"=>"1"    }}