问题
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