ruby - Create Ranges from Array of Dates -
how can following code takes array of dates , returns array of ranges dates:
def get_ranges(dates) sets = [] current_set = [] dates.each |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
running following:
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)
produces following result:
=> [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]
would appreciate help.
update
basically, result should array of consecutive date ranges.
your result looks little odd; there ranges start , end itself. if trying produce array of ranges in each range starts element @ index , ends element @ index + 1, that:
dates.each_cons(2).map { |dates| (dates[0]..dates[1]) }
Comments
Post a Comment