Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Bill Siggelkow http://billonrails.blogspot.com

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Convert Ruby Array to Ranges

# 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
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS