I would suggest using Enumerable#group_by