Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

[
  #<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"
]

A possible (but nasty) solution:

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

This does not seem very straight forward to me and so I'm looking for an alternative. Another solution would be to store everything in a hash and use the name as an index. But that would require to iterate two times and does also not seem to be the most elegant solution. It would be awesome if anyone had an idea how to iterate elegantly.

Kind Regards, Sebastian

PS: I just realized that all the other items with the same name attribute have to be known to the actually processed item. So my solution won't even work for that. :-(

like image 301
YMMD Avatar asked Dec 21 '22 10:12

YMMD


1 Answers

Try this:

array.group_by(&:name).map{|k, v| v.first}
like image 166
Dogbert Avatar answered May 12 '23 12:05

Dogbert