How do I summarize array of integers as an array of ranges?

后端 未结 5 2193
-上瘾入骨i
-上瘾入骨i 2020-12-16 02:48

I\'d like to take input such as:

[1,2,4,5,6,7,9,13]

and turn it into something like the following:

[[1,2],[4,7],[9,9],[13,1         


        
5条回答
  •  被撕碎了的回忆
    2020-12-16 03:27

    This is almost straight from the enumerable#slice_before method documentation:

    ar = [1,2,4,5,6,7,9,13]
    prev = ar[0]
    ar.slice_before{|e|prev,prev2 = e,prev; prev2.succ != e}.map{|a|a.first..a.last}
    #=> [1..2, 4..7, 9..9, 13..13]
    

    This should work with characters, dates, anything with a .succ method.

提交回复
热议问题