Ruby组整数数组到范围数组

时间:2017-10-19 07:15:00

标签: arrays ruby collections range

有没有一种优雅的方法可以将整数数组分组到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]

1 个答案:

答案 0 :(得分:2)

鉴于原始数组已经排序且未经过选择:

[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]