I have an array with several time ranges inside:
[Tue, 24 May 2011 08:00:00 CEST +02:00..Tue, 24 May 2011 13:00:00 CEST +02:00,
Tue, 24 May 2011 16:30:00 CEST +02:00..Tue, 24 May 2011 18:00:00 CEST +02:00,
Tue, 24 May 2011 08:00:00 CEST +02:00..Tue, 24 May 2011 09:00:00 CEST +02:00,
Tue, 24 May 2011 15:30:00 CEST +02:00..Tue, 24 May 2011 18:00:00 CEST +02:00]
I want to get the same array with the overlapping time ranges combined, so the output for this case will be:
[Tue, 24 May 2011 08:00:00 CEST +02:00..Tue, 24 May 2011 13:00:00 CEST +02:00,
Tue, 24 May 2011 15:30:00 CEST +02:00..Tue, 24 May 2011 18:00:00 CEST +02:00]
So it creates a new time range when to time ranges overlap, and so on. If they don´t overlap the will be keep separated. Another example:
Input:
[Tue, 24 May 2011 08:00:00 CEST +02:00..Tue, 24 May 2011 13:00:00 CEST +02:00,
Tue, 24 May 2011 16:00:00 CEST +02:00..Tue, 24 May 2011 18:00:00 CEST +02:00]
Output (will be the same because they don´t overlap):
[Tue, 24 May 2011 08:00:00 CEST +02:00..Tue, 24 May 2011 13:00:00 CEST +02:00,
Tue, 24 May 2011 16:00:00 CEST +02:00..Tue, 24 May 2011 18:00:00 CEST +02:00]
I was thinking in some recursive approach, but I need some guidance here...
Searching a little bit I have found a code that does the trick:
A sample (working with time ranges too!):
Found here: http://www.ruby-forum.com/topic/162010
I made a minor update to the answer from Wayne Conrad to handle edge cases involved with open-ended arrays (created with ... operator instead of .. operator).
I changed the name to
merge_continuous_ranges
since while ranges like0...1
and1..2
do not overlap, their combined ranges are continuous, so it makes sense to combine them:The gem range_operators does a wonderful job by adding missing features to the Ruby
Range
class. It is way smaller than adding the whole facets gem.I your case the solution would be the
rangify
method, which is added to theArray
class and would do exactly what you are looking for.