, #

Ruby group_by object?

I have an array or different objects, and I want to group 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 group objects in one array?

+7
source share
1 answer

Do you want to do something like this?

 all.group_by(&:class) 

What will group objects in an array by class name

EDIT for comments

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

The key is a grouping element, and obj is the set for the key, so it will cycle through each group in the group and display objects inside this group

Also you can easily sort inside grouping

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

All Articles