简体   繁体   中英

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.

ps: happy new 2015 year

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

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)}

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] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM