我有一个哈希数组,我想打破一个子数组数组。
拆分的触发器是: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" }
是否有快速导轨功能可以实现这一点,或者我需要使用控制中断类型循环,就像我多年前使用Cobol一样......:)
答案 0 :(得分:2)
您可能希望使用Enumerable.group_by
功能对数据进行分组。
master.group_by { |item| item[:group] }
这会产生
{
"Red" => [{ id: 7, group: "Red", name: "Grace" },...],
"Black" => ...,
...
}
答案 1 :(得分:1)
master.group_by{|h| h[:group]}