2
我有一個事件數組,我想根據event_date(它返回一個Time對象)將它們分成一個二維數組。但我希望在日期的那一天。這是我到目前爲止:什麼是按日期排序的更好方法?
def divide_events_by_day(events)
# Sort, so we can start with the first day.
events = events.sort { |x,y| x.event_date <=> y.event_date }
days = []
current_date = events[0].event_date # A Time object.
# With meaningful hours and minutes.
while events.length > 0 do
# Find events for the current date.
day_events = events.select { |e|
(e.event_date.year == current_date.year) &&
(e.event_date.yday == current_date.yday)
}
# Move them to their subarray.
days << day_events
events = events - day_events
# Advance the current_date by one day.
current_date = (current_date + (60 * 60 * 24))
end
days
end
任何建議,使其更簡單或更快?
更好的辦法比我,應該是==,也不需要將代碼添加到一年中的某一天進行分解... – 2009-03-06 00:34:31