什么是按日期排序的更好方法?

时间:2009-03-05 23:54:05

标签: ruby date sorting

我有一个事件数组,我想根据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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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