Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is how I'd go about it:</p> <pre><code>require 'time' FIVE_MINUTES = 60 * 5 timestamps = [ '2013-06-17 19:47:12', '2013-06-17 19:40:01', '2013-06-17 19:42:53', '2013-06-17 19:12:27', '2013-06-17 19:45:42', '2013-06-17 19:14:17' ].map{ |s| Time.parse(s) }.sort ranges = [timestamps.first .. timestamps.shift] loop do break if timestamps.empty? if (timestamps.first - ranges.last.max) &lt;= FIVE_MINUTES ranges[-1] = (ranges.last.min .. timestamps.shift) else ranges &lt;&lt; (timestamps.first .. timestamps.shift) end end pp ranges.map{ |r| Hash[ :range_start, r.min, :range_end, r.max ] } </code></pre> <p>Which is an array of hashes:</p> <pre><code>[ { :range_start =&gt; 2013-06-17 19:12:27 -0700, :range_end =&gt; 2013-06-17 19:14:17 -0700 }, { :range_start =&gt; 2013-06-17 19:40:01 -0700, :range_end =&gt; 2013-06-17 19:47:12 -0700 } ] </code></pre> <p>I converted the DateTime strings to Time values because you get an integer in seconds when subtracting them. That worked well when comparing to <code>FIVE_MINUTES</code>. If you need DateTime objects, you can convert them easily using:</p> <pre><code>pp ranges.map{ |r| Hash[ :range_start, r.min.to_datetime, :range_end, r.max.to_datetime ] } </code></pre> <p>Which now looks like:</p> <pre><code>[ { :range_start=&gt; #&lt;DateTime: 2013-06-17T19:12:27-07:00 ((2456462j,7947s,0n),-25200s,2299161j)&gt;, :range_end=&gt; #&lt;DateTime: 2013-06-17T19:14:17-07:00 ((2456462j,8057s,0n),-25200s,2299161j)&gt; }, { :range_start=&gt; #&lt;DateTime: 2013-06-17T19:40:01-07:00 ((2456462j,9601s,0n),-25200s,2299161j)&gt;, :range_end=&gt; #&lt;DateTime: 2013-06-17T19:47:12-07:00 ((2456462j,10032s,0n),-25200s,2299161j)&gt; } ] </code></pre> <p>I sorted the array because that made it pretty straightforward to find values that were within the five minute boundaries of each other. That results in the ranges being sorted also.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload