Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/natural/array.rb

Overview

Instance Method Summary collapse

Instance Method Details

#to_rangesObject



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/natural/array.rb', line 3

def to_ranges
  array = self.compact.uniq.sort
  ranges = []
  if !array.empty?
    # Initialize the left and right endpoints of the range
    left, right = self.first, nil
    array.each do |obj|
      # If the right endpoint is set and obj is not equal to right's successor 
      # then we need to create a range.
      if right && obj != right.succ
        ranges << Range.new(left,right)
        left = obj
      end
      right = obj
    end
    ranges << Range.new(left,right)
  end
  ranges
end