Convert Ruby Array to Ranges
# Converts an array of values (which must respond to #succ) to an array of ranges. For example,
# [3,4,5,1,6,9,8].to_ranges => [1,3..6,8..9]
1 2 class Array 3 def to_ranges 4 array = self.compact.uniq.sort 5 ranges = [] 6 if !array.empty? 7 # Initialize the left and right endpoints of the range 8 left, right = self.first, nil 9 array.each do |obj| 10 # If the right endpoint is set and obj is not equal to right's successor 11 # then we need to create a range. 12 if right && obj != right.succ 13 ranges << Range.new(left,right) 14 left = obj 15 end 16 right = obj 17 end 18 ranges << Range.new(left,right) 19 end 20 ranges 21 end 22 end