anndrew78
anndrew78

Reputation: 196

how to create an array with ranges using an array with integer in ruby(rails)?

i have an array with sorted integers

array = [1,4,10,14,22]

i would like to create from array before an

array_with_ranges = [[0..1],[2..4],[5..10],[11..14],[15..22]]

i cant create a right iterator, i'm newbie in rails. In every ranges i have end_range value, but don't know how to set a start_range value? in most ranges in array_with_ranges the start_range is a end_range before +1 (except [0..1])

any solutions or ideas?

thank you for answers.

p.s.: happy new 2015 year

Upvotes: 0

Views: 208

Answers (3)

Nick Veys
Nick Veys

Reputation: 23939

Just keeping track of the previous value takes care of it:

2.1.5 :001 > array = [1,4,10,14,22]
 => [1, 4, 10, 14, 22] 
2.1.5 :002 > previous = 0
 => 0 
2.1.5 :003 > array.map { |i| rng = previous..i; previous = i + 1; rng }
 => [0..1, 2..4, 5..10, 11..14, 15..22] 

I imagine there's a slicker way to do it though.

edit: Of course there is, building on @steenslag's answer:

2.1.5 :001 > array = [1, 4, 10, 14, 22]
 => [1, 4, 10, 14, 22] 
2.1.5 :002 > ([-1] + array).each_cons(2).map { |a,b| (a + 1)..b }
 => [0..1, 2..4, 5..10, 11..14, 15..22] 

Upvotes: 0

steenslag
steenslag

Reputation: 80065

Add a helper value of -1, later on remove it.

array = [1,4,10,14,22]
array.unshift(-1)
ranges = array.each_cons(2).map{|a,b| a+1..b} #=>[0..1, 2..4, 5..10, 11..14, 15..22]

array.shift

Upvotes: 2

Grych
Grych

Reputation: 2901

You can iterate on all elements of the array and save the previous value in the external variable, like this:

last = -1 
array.collect {|x| prev = last; last = x; (prev+1..x)}

Upvotes: 1

Related Questions