Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 825
Matt Elhotiby Avatar asked Jan 22 '11 15:01

Matt Elhotiby


People also ask

What is group_ by in rails?

Group by in ruby rails programming is one of the data types. The collection of enumerable sets is preliminary to group the results into a block. For instance, we can group the records by date. The group_by function in Ruby allows us to group objects by an arbitrary attribute.

What does .shift do in Ruby?

The shift() is an inbuilt function in Ruby returns the element in the front of the SizedQueue and removes it from the SizedQueue. Parameters: The function does not takes any element.

What is enumerable in Ruby?

Enumeration refers to traversing over objects. In Ruby, we call an object enumerable when it describes a set of items and a method to loop over each of them.


1 Answers

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
like image 182
Jimmy Avatar answered Sep 28 '22 02:09

Jimmy