0

我有一个具有相同密钥Array的es,用于存储人们的数据。Hash

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

有一个简单的解决方案吗?

4

4 回答 4

4

您可以将块传递给uniqor uniq!,块返回的值用于比较两个条目是否相等:

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}]
于 2013-05-03T08:52:47.543 回答
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}]
于 2013-05-03T08:54:16.190 回答
0
a.delete_if do |h|
  a.select{|i| i[:name] == h[:name] and i[:surname] == h[:surname] }.count > 1
end
于 2013-05-03T08:55:40.497 回答
0
unique_people = {}
person_array.each do |person|
  unique_people["#{person[:name]} #{person[:surname]}"] = person
end

array_of_unique_people = unique_people.values

这应该可以解决问题。

于 2013-05-03T08:53:47.027 回答