我真的不知道我是否得到了你想要做的事情,但我会根据我得到的来解释。
我使用Hash 来保存数据,但您可能会使用您的模型。
data = [{ id: 1, price: 2, pax: 2, event_room_numer: 1, start_date: "10-10-2015".to_date, end_date: "12-10-2015".to_date }, { id: 2, price: 3, pax: 12, event_room_numer: 3, start_date: "08-10-2015".to_date, end_date: "16-10-2015".to_date }, { id: 1, price: 2, pax: 20, event_room_numer: 3, start_date: "12-10-2015".to_date, end_date: "16-10-2015".to_date }]
在下面的代码中,我创建了一个 Hash 来保存特定日期的事件。
events_on_day = {}
data.each do |dado|
(dado[:start_date]..dado[:end_date]).each do |date|
events_on_day[date] ||= []
events_on_day[date] << dado
end
end
然后我们根据天数(键)对Hash 进行排序。
sorted_events_on_day = events_on_day.sort.to_h
最后我们得到了统计数据。
statistics = sorted_events_on_day.map do |date, events|
total_price, total_pax = 0, 0
total_event = events.count # count the events on the day
events.each do |event|
total_price += event[:price] # sum price for the day
total_pax += event[:pax] # sum pax for the day
end
[date, total_event, total_price, total_pax]
end
在statistics 数组中,我们将拥有每天的数据。像这样的东西(对于data 输入):
data total_event total_price total_pax
2015-10-08 1 3 12
2015-10-09 1 3 12
2015-10-10 2 5 14
2015-10-11 2 5 14
2015-10-12 3 7 34
2015-10-13 2 5 32
2015-10-14 2 5 32
2015-10-15 2 5 32
2015-10-16 2 5 32