2013-05-03 108 views
0

我有一个ArrayHash es具有相同的键值,用于存储人员的数据。删除具有相同键值的哈希值

我想删除具有相同值的密钥:name:surname的哈希值。其余的值可能不同,因此在数组上调用uniq!将不起作用。

有没有简单的解决方案呢?

回答

4

你可以传递到uniquniq!块,由块返回的值是用来比较两个条目平等:

irb> people = [{name: 'foo', surname: 'bar', age: 10}, 
       {name: 'foo', surname: 'bar' age: 11}] 
irb> people.uniq { |p| [p[:name], p[:surname]] } 
=> [{:name=>"foo", :surname=>"bar", :age=>10}] 
0
unique_people = {} 
person_array.each do |person| 
    unique_people["#{person[:name]} #{person[:surname]}"] = person 
end 

array_of_unique_people = unique_people.values 

这应该做的伎俩。

1
arr=[{name: 'john', surname: 'smith', phone:123456789}, 
    {name: 'thomas', surname: 'hardy', phone: 671234992}, 
    {name: 'john', surname: 'smith', phone: 666777888}] 
# [{:name=>"john", :surname=>"smith", :phone=>123456789}, 
# {:name=>"thomas", :surname=>"hardy", :phone=>671234992}, 
# {:name=>"john", :surname=>"smith", :phone=>666777888}] 

arr.uniq {|h| [h[:name], h[:surname]]} 
# [{:name=>"john", :surname=>"smith", :phone=>123456789}, 
# {:name=>"thomas", :surname=>"hardy", :phone=>671234992}] 
+0

我认为只会独特的姓氏。你想在块内使用'+',而不是'&&'。事实上,你可能想要构建一个数组进行比较。 – 2013-05-03 08:57:51

+0

@NeilSlater正确 – 2013-05-03 08:59:22

+0

卡罗尔亚当斯和卡罗拉水坝不高兴。 – steenslag 2013-05-03 14:07:24

0
a.delete_if do |h| 
    a.select{|i| i[:name] == h[:name] and i[:surname] == h[:surname] }.count > 1 
end