title: Select consecutive integers from array in Ruby
body: <p>I want to select consecutive integers from an array, for example:</p>
  
  <p>Input: (doesn't have to be sorted)</p>
  
  <pre><code>array = [1, 3, 6, 7, 8, 9, 10, 12, 13, 17]
  </code></pre>
  
  <p>Expected output:</p>
  
  <pre><code>#=&gt; [6, 7, 8, 9, 10, 12, 13]
  </code></pre>
  
  <p>This is my code so far:</p>
  
  <pre><code>array = [1, 3, 9, 6, 7, 10, 8, 12, 13, 17]
  newarray = []
  z = 0
  array.sort.each_cons(2) do |x, y|
    if y == x + 1
      if z == 0
        newarray.insert(0, x, y)
      else
        newarray.push(y)
      end
    end
    z = z + 1
  end
  
  newarray #=&gt; [7, 8, 9, 10, 13]
  </code></pre>
  
  <p>As you can see, <code>6</code> and <code>12</code> are missing.</p>
  
  <p>What's wrong with my code and - besides the bug - is there a better way to write it?</p>