删除散列哈希中的重复条目

时间:2015-01-13 06:32:52

标签: ruby

请你给我一个解决方案:

hash_list = {
  "a"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false"},
  "b"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false"},
  "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"},
  "c"=>{"unit_id"=>"43", "dep_id"=>"154", "_destroy"=>"false"},
  "d"=>{"unit_id"=>"42", "dep_id"=>"154", "_destroy"=>"false"}
}

3 个答案:

答案 0 :(得分:3)

你可以做到

hash_list.invert.invert

Hash#invert创建一个新哈希,其中旧哈希的值是新哈希的键,这将删除旧哈希的任何重复值。对invert的第二次调用会回转。

这并不能控制您删除重复值的哪些键。

答案 1 :(得分:1)

你可以写

hash_list = {
  "a"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false"},
  "b"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false"},
  "c"=>{"unit_id"=>"43", "dep_id"=>"154", "_destroy"=>"false"},
  "d"=>{"unit_id"=>"42", "dep_id"=>"154", "_destroy"=>"false"}
}
hash_list.to_a
         .uniq { |_, hash| hash.values_at('unit_id', 'dep_id', '_destroy') }
         .to_h
# => {"a"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false"}, "c"=>{"unit_id"=>"43", "dep_id"=>"154", "_destroy"=>"false"}, "d"=>{"unit_id"=>"42", "dep_id"=>"154", "_destroy"=>"false"}}

注意:如果内部哈希只有post中显示的键,那么Hash#values就足够了。

答案 2 :(得分:0)

也可以写下以下内容,但弗雷德里克的解决方案显然是使用的解决方案:

Hash[hash_list.group_by { |_,v| v }.map { |_,v| v.first }]
  #=> {"a"=>{"unit_id"=>"43", "dep_id"=>"153", "_destroy"=>"false"},
  #    "c"=>{"unit_id"=>"43", "dep_id"=>"154", "_destroy"=>"false"},
  #    "d"=>{"unit_id"=>"42", "dep_id"=>"154", "_destroy"=>"false"}}

对于Ruby 1.9+,这将保留所有值为k=>v的键值对中的第一个键值对v