Ruby: Iterate through an array of objects, ignore elements with duplicate attributes

I have an array of objects in ruby, and I want to iterate over it, ignoring every object that has a name that has already been processed. For instance:

[ #<Item name: "Item 1", content: "a">, #<Item name: "Item 1", content: "b">, #<Item name: "Item 2", content: "c">, #<Item name: "Item 3", content: "d">, #<Item name: "Item 3", content: "e"> ] 

Should be reduced to

 [ #<Item name: "Item 1">, # Should know that it belongs to content: "a" and "b" #<Item name: "Item 2">, # Should know that it belongs to content "c" #<Item name: "Item 3"> # Should know that it belongs to content: "d" and "e" ] 

Possible (but nasty) solution:

 processed = [] items.each do |item| next if processed.include?(item.name) processed << item.name # Output ... 

This does not seem to me very direct, and therefore I am looking for an alternative. Another solution would be to keep everything in a hash and use the name as an index. But this will require repeating the iteration twice and does not appear to be the most elegant solution. It would be great if anyone had an idea how elegantly iterative.

Regards, Sebastian

PS : I realized that all other elements with the same name attribute should be known to the actually processed element . So my solution will not work for this .: - (

+4
source share
2 answers

Try the following:

 array.group_by(&:name).map{|k, v| v.first} 
+9
source
 a = [ "a", "a", "b", "b", "c" ] a.uniq #=> ["a", "b", "c"] 
+2
source

All Articles