Arwa
Arwa

Reputation: 587

Ruby: Group array of array of object

I would like to group an array of arrays of objects by object attribute.

So, if we have

array =[[object1, object2], [object3], [object4, object5, object6]]

and this object has an attribute say "source". Now assume each object has the following source value:

object1> source=source1
object2> source=source2
object3> source=source2
object4> source=source1
object5> source=source1
object6> source=source3

I want to group the arrays that are inside "array" by source attribute.

so I would like to have:

source1 => [object1, object2], [object4, object5, object6]
source2 => [object1, object2] 
source3 => [object4, object5, object6]

for source2, I don't care about array of size 1 so I don't want to add [object3]

Any help?

Upvotes: 1

Views: 479

Answers (1)

Mark Thomas
Mark Thomas

Reputation: 37527

The key thing, which became apparent after your edit, is that you have already grouped your objects, and you want to bucket your groups into potentially more than one bucket based on the objects in each grouping, so this isn't a pure group_by algorithm. Here is one possible solution:

First, create a hash to hold your groups. This sets an empty array as the default value:

sources = Hash.new {|h,k| h[k] = Array.new }

Then reject the ones you don't care about (see Enumerable#reject).

array.reject{|group| group.size == 1}

Finally, iterate through the groups, collecting their sources and adding the group to the appropriate source in the hash. Full example:

sources = Hash.new {|h,k| h[k] = Array.new }

array.reject{|group| group.size == 1}.each do |group|
  group.collect{|group| group.source}.uniq.each do |source|
    sources[source] << group
  end
end

Upvotes: 2

Related Questions