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. :-(
Try this:
array.group_by(&:name).map{|k, v| v.first}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With