Matt Elhotiby
Matt Elhotiby

Reputation: 44066

Ruby group_by object?

I have an array or different objects and I want to group by objects. For example

 => [#<Graphic id: 3...">, #<Collection id: 1....">, #<Category id:...">, #<Volume id: 15...">] 
 all.size
 => 4 

I tried

all.group_by(Object) 

but that didn't work...any ideas on how to groupby objects in one array?

Upvotes: 8

Views: 11508

Answers (1)

Jimmy
Jimmy

Reputation: 9815

Are you looking to do something like this?

all.group_by(&:class)

Which will group the objects in array by their class name

EDIT for comment

all.group_by(&:class).each do |key, group|
   group.each{|item| puts item}
end

Key is the grouping element and obj is the collection for the key, so this would loop through each group in the grouping and list the objects within that group

Also you could sort within the groupings pretty easily too

all.group_by(&:class).each do |key, group|
    group.sort_by(&:attribute).each{|item| puts item}
end

Upvotes: 20

Related Questions