1

Is there an elegant way to group an integer array to a range array in Ruby?

range1 = [*39..45]
#=> [39, 40, 41, 42, 43, 44, 45]

range2 = [*49..52]
#=> [49, 50, 51, 52]

range = range1 + range2
#=> [39, 40, 41, 42, 43, 44, 45, 49, 50, 51, 52]

range.build_ranges
#=> [39..45, 49..52]
Marco Roth
  • 184
  • 4
  • 11
  • Also here: https://stackoverflow.com/questions/23840815/grouping-consecutive-numbers-in-an-array – tokland Oct 19 '17 at 07:40

1 Answers1

2

Yes.

Given that the original array is already sorted and uniqued:

[39, 40, 41, 42, 43, 44, 45, 49, 50, 51, 52]
.chunk_while{|i, j| i.next == j}
.map{|a| a.first..a.last}
# => [39..45, 49..52]
sawa
  • 165,429
  • 45
  • 277
  • 381