Skip to content

Instantly share code, notes, and snippets.

@jcsrb
Created July 7, 2011 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcsrb/1069307 to your computer and use it in GitHub Desktop.
Save jcsrb/1069307 to your computer and use it in GitHub Desktop.
turn a Array of Fixnums into Array of Ranges
class Array
# Array#to_ranges
# Converts an array of values to an array of ranges. For example,
# [2, 3, 33, 34, 110, 1, 111, 112, 4].to_ranges => [1..4, 33..34, 110..112]
def to_ranges
return nil unless self.all?{|item| item.is_a?Fixnum}
self.sort.uniq.inject([]) do |spans, n|
if spans.empty? || spans.last.last != n - 1
spans + [n..n]
else
spans[0..-2] + [spans.last.first..n]
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment