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

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.