title: ruby group ranges that are close to each other
body: <p>I have these ranges:</p>
  
  <pre><code>X = [10..17,21..34,40..117,384..399,407..455,989..1013]
  </code></pre>
  
  <p>What I need is:
  if the first number of the second range minus the last number of the first range is less than 10, then group them together, else include the range.
  What I need is the following:</p>
  
  <pre><code>result = [[10..17,21..34,40..117],[384..399,407..455],[989..1013]]
  </code></pre>
  
  <p>what I've done is this but this does not group more than two together.</p>
  
  <pre><code>Y = []
  X.each_cons(2) do |r1,r2|
    if (r2.first - r1.last) &lt; 10
        Y &lt;&lt; ((r1.last - r1.first) + (r2.last - r2.first)
    else
        Y &lt;&lt; (r1.last - r1.first)
    end
  end
  
  # Y = [[10..17,21..34,40..117],[384..399,407..455],[989..1013]]
  </code></pre>
  
  <p>I like to also then add up all ranges within each element:</p>
  
  <pre><code>Y = [97, 63, 24]
  </code></pre>
  
  <p>Any help will be appreciated. Thanks in advance.</p>