Ruby group_by object?

10,924

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
Share:
10,924
Matt Elhotiby
Author by

Matt Elhotiby

Interests: Javascript, React and Rails

Updated on June 28, 2022

Comments

  • Matt Elhotiby
    Matt Elhotiby almost 2 years

    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?

  • Matt Elhotiby
    Matt Elhotiby over 13 years
    yes but that gives me an ordered hash ...how do i use that in the view. I want to display all the Collections first then all the Graphics and so on....so basically i want to use this array to group by the models and then loop through them but how do you loop through this .... => #<OrderedHash {Category(i
  • Matt Elhotiby
    Matt Elhotiby over 13 years
    thanks Jimmy that is a great answer...do you know how to group them into 4 arrays all with the appropriate objects...so for example one array with @graphics and the next with @collections and so on...