Split an array of objects by common parameters in Ruby

I have an array of @objects objects and would like to split it into an array of arrays based on the parameter, resulting in an array, where each record is an array of objects, all of which have object.property the same.

@objects = [obj1, obj2, obj3, obj4, obj5]
obj1.property = a
obj2.property = a
obj3.property = b
obj4.property = b
obj5.property = c
array = [[obj1, obj2,], [obj3, obj4], [obj5]]
+3
source share
1 answer
@objects.group_by { |obj| obj.property }.values
+7
source

Source: https://habr.com/ru/post/1764023/


All Articles