我有一个已排序的数组,我希望按属性对这些对象进行分组,但前提是它们在数组中相邻。
a
按start
属性排序。
a = [{name: "joe", start: "9am", end: "10am"},
{name: "joe", start: "10am", end: "11am"},
{name: "harry", start: "11am", end: "12pm"},
{name: "harry", start: "12pm", end: "1pm"},
{name: "harry", start: "1pm", end: "2pm"},
{name: "joe", start: "2pm", end: "3pm"},
{name: "joe", start: "3pm", end: "4pm"}]
我想按name
属性对相邻对象进行分组,结果如下:
a = [[{name: "joe", start: "9am", end: "10am"},{name: "joe", start: "10am", end: "11am"}],
[{name: "harry", start: "11am", end: "12pm"},{name: "harry", start: "12pm", end: "1pm"},{name: "harry", start: "1pm", end: "2pm"}],
[{name: "joe", start: "2pm", end: "3pm"},{name: "joe", start: "3pm", end: "4pm"}]]
答案 0 :(得分:1)
这应该做:
a.chunk {|hash| hash[:name]}.map(&:last)