I'm trying to figure out how I can change array of integers into array of ranges. For example I want to take this array:
ar = [0, 49, 14, 30, 40, 23, 59, 101]
into
ar = [0..49, 14..30, 40..23, 59..101]
Given array always will be even. I want to take each two values as borders of ranges.
I have tried to seperate it for two arrays. One with odd indexes second with even.
a = ar.select.with_index{|_,i| (i+1) % 2 == 1}
b = ar.select.with_index{|_,i| (i+1) % 2 == 0}
I don't have an idea how to use them to create ranges, also I would like to avoid creating redundant variables like a
and b
.
I don't want to sort any values. Range 40..23
is intentional.
ar.each_slice(2).map { | a, b | a..b }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With