0

I have an Array of Hashes with the same keys, storing people's data.

I want to remove the hashes that have the same values for the keys :name and :surname. The rest of the values can differ, so calling uniq! on array won't work.

Is there a simple solution for this?

4 Answers 4

4

You can pass a block to uniq or uniq!, the value returned by the block is used to compare two entries for equality:

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}]
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}]
3
  • I think that will only unique the surname. You want +, not && inside the block. In fact, you probably want to construct an array for comparison. May 3, 2013 at 8:57
  • carol adams and carola dams are not happy.
    – steenslag
    May 3, 2013 at 14:07
  • @steenslag hope they are happy now ;) May 4, 2013 at 15:31
0
unique_people = {}
person_array.each do |person|
  unique_people["#{person[:name]} #{person[:surname]}"] = person
end

array_of_unique_people = unique_people.values

This should do the trick.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.