Skip to content

Instantly share code, notes, and snippets.

@Bjoernsen
Bjoernsen / Array_to_ranges
Created June 25, 2014 08:08
Add method to_ranges to Array Class
# 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]