这是我在 Ruby 中使用的一个对象。这是一堆按日期排序的事件,但是当对象中有两个或多个具有相同 event_type 的对象彼此相邻时,我想将对象嵌套更深一层。
@events = [
{ :id => 1, :event_type => "B", :created_at => "2013-09-30 14:44:24 UTC"},
{ :id => 2, :event_type => "A", :created_at => "2013-09-29 14:44:24 UTC"},
{ :id => 3, :event_type => "A", :created_at => "2013-09-28 14:44:24 UTC"},
{ :id => 4, :event_type => "C", :created_at => "2013-09-27 14:44:24 UTC"},
{ :id => 5, :event_type => "C", :created_at => "2013-09-26 14:44:24 UTC"},
{ :id => 6, :event_type => "A", :created_at => "2013-09-25 14:44:24 UTC"}
]
我想把它变成这样:
@events = [
{ :id => 1, :event_type => "B", :created_at => "2013-09-30 14:44:24 UTC"},
{ :grouped_events => [
{ :id => 2, :event_type => "A", :created_at => "2013-09-29 14:44:24 UTC"},
{ :id => 3, :event_type => "A", :created_at => "2013-09-28 14:44:24 UTC"}
]
},
{ :grouped_events => [
{ :id => 4, :event_type => "C", :created_at => "2013-09-27 14:44:24 UTC"},
{ :id => 5, :event_type => "C", :created_at => "2013-09-26 14:44:24 UTC"}
]
},
{ :id => 6, :event_type => "A", :created_at => "2013-09-25 14:44:24 UTC"}
]
我需要整个对象来保持嵌套对象按日期排序,但如果有 2 个或更多事件聚集在一起,我希望它们变成一个数组,如示例输出所示。这似乎是一个简单的问题,但我似乎无法弄清楚。