【发布时间】:2017-08-31 07:54:09
【问题描述】:
通过这个函数,我可以生成所需的范围:
first_index = 0
last_index = 3
ranges = []
while first_index != last_index
while last_index != 0
if first_index < last_index
ranges << (first_index..last_index)
end
last_index -= 1
end
first_index += 1
last_index = 3
end
p ranges
输出是:
[0..3, 0..2, 0..1, 1..3, 1..2, 2..3]
我需要在嵌套while 循环完成后恢复它的输出。所以在这个例子中,我需要:
[0..3, 0..2, 0..1].reverse
[1..3, 1..2].reverse
[2..3].reverse (wouldn't make any different on this, though)
我会得到的输出是:
[0..1, 0..2, 0..3, 1..2, 1..3, 2..3]
我可以在该函数中以某种方式调用reverse 吗? last_index 可以是任何整数。我使用 3 只是为了缩短输出。
【问题讨论】:
-
(0..3).to_a.combination(2).map { |a, b| a..b }按预期顺序返回范围。 -
@Stefan 嗯,这在短短几秒钟内就是一个很好的解决方案。如果您可以写一个带有简短解释的答案,我会接受它,也许有一天这也会对其他人有所帮助..
标签: arrays ruby while-loop reverse