0

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?

3
  • 3
    what is that hiphen supposed to mean between the numbers inside the inner array ? Commented Apr 23, 2014 at 5:49
  • Is [0-10] meant to be [0, 1, ..., 10]? Then what is [30-infinity]? Commented Apr 23, 2014 at 6:05
  • @CarySwoveland The title and the text clearly says it is not. Commented Apr 23, 2014 at 6:12

2 Answers 2

6

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

3 Comments

You have an array of ranges, but the OP asks for an array of arrays (which does not make sense, given the example). You are not answering the OP's question, but it is not your fault. It is the OP's fault.
@sawa Humm,, you are right. I assumed he wanted to get array of ranges.
You could use the shorthand .map { |a,b| a..b } instead of Range.new
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.