2009-03-05 48 views
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 

任何建議,使其更簡單或更快?

回答

2

一開始,你可以嘗試這樣的事:

def divide_events_by_day(events) 
    days = [[]] 
    events.sort_by { |x| x.event_date }.each { |e| 
     if days.last.empty? or days.last.event_date_date == e.event_date.date 
      days.last << e 
      else 
      days << [e] 
      end 
     } 
    days 
    end 

它不會產生空天,但除此之外,你如下相當密切。

我有我的機器上的Time#date方法,但我沒有看到它在一個乾淨的分發版本(1.8.7),所以你可能需要添加類似:

class Time 
    def date 
     to_i/(60*60*24) 
     end 
    end 
+0

更好的辦法比我,應該是==,也不需要將代碼添加到一年中的某一天進行分解... – 2009-03-06 00:34:31

1

這應該是更快:

def divide(events) 
    hash = {} 
    events.each do |event| 
    key = "#{event.event_date.year} #{event.event_date.yday}" 
    hash[key] ||= [] 
    hash[key] << event 
    end 
    hash.to_a.sort do|pair1,pair2| 
    pair1[0] <=> pair2[0] 
    end.map do |pair| 
    pair[1].sort{|x,y| x.event_date <=> y.event_date} 
    end 
end