Dercni
Dercni

Reputation: 1224

Splitting an array into sub arrays

I have an array of hashs that I would like to break into an array of sub arrays.

The trigger for the split is :group

master = []
master << { id: 1, group: "Brown", name: "Fred" }
master << { id: 2, group: "Brown", name: "May" }
master << { id: 3, group: "Brown", name: "Brian" }
master << { id: 4, group: "Black", name: "Sue" }
master << { id: 5, group: "Orange", name: "Helen" }
master << { id: 6, group: "Orange", name: "Peter" }
master << { id: 7, group: "Red", name: "Grace" }
master << { id: 8, group: "Red", name: "Michael" }
master << { id: 9, group: "Red", name: "Paul" }

Is there a quick rails function that can achieve this or do I need to use a control-break type loop as I did with Cobol years ago... :)

Upvotes: 1

Views: 296

Answers (2)

Jakub Arnold
Jakub Arnold

Reputation: 87210

You would want to group your data using the Enumerable.group_by function.

master.group_by { |item| item[:group] }

This would produce

{
  "Red" => [{ id: 7, group: "Red", name: "Grace" },...],
  "Black" => ...,
  ...
}

Upvotes: 2

Fitzsimmons
Fitzsimmons

Reputation: 1581

master.group_by{|h| h[:group]}

Upvotes: 1

Related Questions