Array of integers into array of ranges

心已入冬 提交于 2021-01-27 07:27:06

问题


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.


回答1:


 ar.each_slice(2).map { | a, b | a..b }



回答2:


I would do as @undur_gongor's suggests, but here's another way:

e = ar.to_enum
b = []
loop do
  b << (e.next..e.next)
end
b 
  #=> [0..49, 14..30, 40..23, 59..101]



回答3:


new_ar = []

ar.each_slice(2) do |r|
    new_ar << Range.new(r[0], r[1])
end


来源:https://stackoverflow.com/questions/29031972/array-of-integers-into-array-of-ranges

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!