How to convert an array of number into ranges
ruby, ruby-on-rails
Solution
I would do as below using `Enumerable#slice_before` :
a = [1,2,3,5,6,8,9,10,11,12]
prev = a[0]
p a.slice_before { |e|
prev, prev2 = e, prev
prev2 + 1 != e
}.map{|b,*,c| c ? (b..c) : b }
# >> [1..3, 5..6, 8..12]
Problem
I'm looking to convert an array of numbers in sequence with gaps into an array of multiple ranges in Ruby. Each range should be determined the gaps in the sequence: ``` [1,2,3,5,6,8,9,10,11,12] ``` The expected result would be: ``` [1-3, 5-6, 8-12] ``` I haven't been able to come up with any good ideas for tackling the problem. How can I go about solving this?