2014-06-27 106 views
0

我怎麼能簡單地將下面的代碼這需要日期的數組,並返回範圍爲日期的數組:從日期的陣列創建範圍

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提供幫助。

更新

基本上,結果應該是連續的日期範圍的陣列。

+7

這個問題可能更適合換[代碼審查堆棧交易所(http://codereview.stackexchange.com/ )。 –

+0

「日期」的元素是否有序?我是否正確地假設你得到的結果是你想要的? –

回答

1

你的結果看起來有點奇怪;有一些範圍以自己開始和結束。如果要嘗試以產生範圍的陣列,其中每個範圍索引i與所述元件開始並在索引i + 1與元件端部,這將這樣做:

dates.each_cons(2).map { |dates| (dates[0]..dates[1]) } 
+0

OP的結果是正常的和預期的。 –

+0

該算法的目標是什麼? – kcdragon

0

這應該工作:

sets = [] 
current = [] 
dates.each do |date| 
    if current.empty? || date - current.last == 1 
    current << date 
    else 
    sets << current.first..current.last 
    current = [date] 
    end 
end 
sets << current.first..current.last 

這樣做本質上是相同的代碼,但是有一點清潔劑...

+0

我甚至認爲你可以使用http://ruby-doc.org/core-2.1.2/Enumerable.html#method-i-partition來製作更多的標準 – Sean