Created
June 25, 2014 08:08
-
-
Save Bjoernsen/b38cc5cde2b2c6fc3a0d to your computer and use it in GitHub Desktop.
Add method to_ranges to Array Class
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
# Add the function to_ranges to Array | |
# This funciton reduces an Array of Integer [0,1,2,3,5,8,9,10,20] to | |
# an Array of ranges, arrays, or fixnums | |
# @params [Symbol] type The result can be an Array of Arrays, Ranges, | |
# or an Array with compact, sorted and uniq Fixnums | |
# @example | |
# [0,1,2,3,5,8,9,10,20].to_ranges #=> [[0, 3], [5, 5], [8, 10], [20, 20]] | |
# [0,1,2,3,5,8,9,10,20].to_ranges(:array) #=> [[0, 3], [5, 5], [8, 10], [20, 20]] | |
# [0,1,2,3,5,8,9,10,20].to_ranges(:range) #=> [0..3, 5..5, 8..10, 20..20] | |
# [0,1,2,3,5,8,9,10,20].to_ranges(:other) #=> [0, 1, 2, 3, 5, 8, 9, 10, 20] | |
class Array | |
def to_ranges(type = :array) | |
compact.sort.uniq.inject([]) do |r,x| | |
if type == :array | |
r.empty? || r.last.last.succ != x ? r << [x,x] : r[0..-2] << [r.last.first,x] | |
elsif type == :range | |
r.empty? || r.last.last.succ != x ? r << (x..x) : r[0..-2] << (r.last.first..x) | |
else | |
r << x | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment