I have an array or different objects and I want to group by objects. For example
=> [#&l开发者_运维知识库t;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?
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
精彩评论