我怎麼能簡單地將下面的代碼這需要日期的數組,並返回範圍爲日期的數組:從日期的陣列創建範圍
def get_ranges(dates)
sets = []
current_set = []
dates.each do |date|
if current_set.empty?
current_set << date
else
if current_set.last == date - 1.day
current_set << date
else
sets << current_set
current_set = [date]
end
end
sets << current_set if date == dates.last
end
sets.collect { |set| set.first..set.last }
end
運行以下:
dates = [Date.new(2014, 6, 27), Date.new(2014, 6, 28), Date.new(2014, 6, 29), Date.new(2014, 7, 1), Date.new(2014, 7, 3), Date.new(2014, 7, 4), Date.new(2014, 7, 17)]
puts get_ranges(dates)
產生以下結果:
=> [Fri, 27 Jun 2014..Sun, 29 Jun 2014, Tue, 01 Jul 2014..Tue, 01 Jul 2014, Thu, 03 Jul 2014..Fri, 04 Jul 2014, Thu, 17 Jul 2014..Thu, 17 Jul 2014]
會APPR提供幫助。
更新
基本上,結果應該是連續的日期範圍的陣列。
這個問題可能更適合換[代碼審查堆棧交易所(http://codereview.stackexchange.com/ )。 –
「日期」的元素是否有序?我是否正確地假設你得到的結果是你想要的? –