我有一个Array
Hash
es具有相同的键值,用于存储人员的数据。删除具有相同键值的哈希值
我想删除具有相同值的密钥:name
和:surname
的哈希值。其余的值可能不同,因此在数组上调用uniq!
将不起作用。
有没有简单的解决方案呢?
我有一个Array
Hash
es具有相同的键值,用于存储人员的数据。删除具有相同键值的哈希值
我想删除具有相同值的密钥:name
和:surname
的哈希值。其余的值可能不同,因此在数组上调用uniq!
将不起作用。
有没有简单的解决方案呢?
你可以传递到uniq
或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}]
unique_people = {}
person_array.each do |person|
unique_people["#{person[:name]} #{person[:surname]}"] = person
end
array_of_unique_people = unique_people.values
这应该做的伎俩。
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}]
a.delete_if do |h|
a.select{|i| i[:name] == h[:name] and i[:surname] == h[:surname] }.count > 1
end
我认为只会独特的姓氏。你想在块内使用'+',而不是'&&'。事实上,你可能想要构建一个数组进行比较。 – 2013-05-03 08:57:51
@NeilSlater正确 – 2013-05-03 08:59:22
卡罗尔亚当斯和卡罗拉水坝不高兴。 – steenslag 2013-05-03 14:07:24