Ruby / Rails仅限相邻阵列元素

时间:2015-03-28 22:59:46

标签: ruby-on-rails ruby arrays

我有一个已排序的数组,我希望按属性对这些对象进行分组,但前提是它们在数组中相邻。

astart属性排序。

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"}]]

1 个答案:

答案 0 :(得分:1)

这应该做:

a.chunk {|hash| hash[:name]}.map(&:last)