Question

I have an array of numbers. I want to convert it to an array of ranges. Example:

input = [0,10,20,30]

output = [0..10, 10..20, 20..30, 30..Infinity] 

Is there some direct way to do it in Ruby?

Was it helpful?

Solution

Yes, possible :

input = [0,10,20,30]
(input + [Float::INFINITY]).each_cons(2).map { |a,b| a..b }
 # => [0..10, 10..20, 20..30, 30..Infinity] 

OTHER TIPS

One way:

Code

output = input.zip(input[1..-1] << 1.0/0).map { |r| Range.new(*r) }

Explanation

input = [0,10,20,30]

a = input[1..-1]
  #=> [10, 20, 30]

b = a << 1.0/0
  #=> [10, 20, 30, Infinity]

c = input.zip(b)
  #=> [[0, 10], [10, 20], [20, 30], [30, Infinity]]

output = c.map { |r| Range.new(*r) }
  #=> [0..10, 10..20, 20..30, 30..Infinity]

Possible alternative

If you instead wanted an array of arrays, you would just change the block:

output = input.zip(input[1..-1] << 1.0/0).map { |f,l| [f..l] }
  #=> [[0..10], [10..20], [20..30], [30..Infinity]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top