开发者

Divide array of objects by common parameters in Ruby

开发者 https://www.devze.com 2023-01-15 17:54 出处:网络
I have an array of objects @objects and would like to split this into an array of arrays based on a parameter, ending up with an array where each entry is 开发者_如何转开发an array of objects all of w

I have an array of objects @objects and would like to split this into an array of arrays based on a parameter, ending up with an array where each entry 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]]


@objects.group_by { |obj| obj.property }.values
0

精彩评论

暂无评论...
验证码 换一张
取 消