如何从散列哈希中删除重复值

时间:2015-06-03 08:41:17

标签: ruby ruby-on-rails-4 hash

我需要一个唯一的哈希值,"one"的值永远不会重复。

例如,

hash= {"1"=>{"one"=>1,"two"=>2},
   "2"=>{"one"=>1,"two"=>3},
   "3"=>{"one"=>2,"two"=>3},
   "4"=>{"one"=>1,"two"=>2}}

然后结果应该是,

hash= {"1"=>{"one"=>1,"two"=>2},
    "3"=>{"one"=>2,"two"=>3}}

3 个答案:

答案 0 :(得分:5)

(可读)单行:

hash.to_a.uniq {|(_,v)| v['one']}.to_h
# {"1"=>{"one"=>1, "two"=>2}, "3"=>{"one"=>2, "two"=>3}}

答案 1 :(得分:2)

hash.inject({}) do |memo, (k, v)| 
  memo[k] = v unless memo.values.any? do |mv| 
                       mv['one'] == v['one']
                     end
  memo
end

#⇒ {
#    "1" => {
#      "one" => 1,
#      "two" => 2
#    },
#    "3" => {
#      "one" => 2,
#      "two" => 3
#    }
#  }

答案 2 :(得分:2)

ones_values = {}
hash.delete_if do |key, value|
  ones_values[value["one"]] ? true : (ones_values[value["one"]] = true) && false
end