Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of integers into array of ranges

Tags:

arrays

range

ruby

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.

like image 965
Gregy Avatar asked Dec 08 '22 04:12

Gregy


1 Answers

 ar.each_slice(2).map { | a, b | a..b }
like image 133
undur_gongor Avatar answered Dec 27 '22 11:12

undur_gongor