Created
July 7, 2011 11:08
-
-
Save jcsrb/1069307 to your computer and use it in GitHub Desktop.
turn a Array of Fixnums into Array of Ranges
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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