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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With