【发布时间】:2016-03-26 11:12:45
【问题描述】:
我想根据运行时确定的条件跳过循环 x 次。我该怎么做?
for i in (0..5)
if i==0
3.times {next} # i=i+3 also doesnt work
end
puts i
end
期待输出
3
4
5
编辑:
澄清一下,问题是 condition(即 i==0)和跳过 x 次迭代都是在运行时动态确定的,更复杂的例子:
condition = Array.new(rand(1..100)).map{|el| rand(1..10000)} #edge cases will bug out
condition.uniq!
for i in (0..10000)
if condition.include? i
rand(1..10).times {next} # will not work
end
puts i
end
【问题讨论】:
-
不确定函数的确切输入和输出是什么。在您的示例中,为什么不直接使用
(3..5).each {|i| puts i} -
@LeiChen,这显然应该这样做,所以为什么不发布答案呢?也许
def skip_first(range, nbr_to_skip)。 -
请看我更复杂的例子
-
对于您的“复杂”示例,我希望提前计算一个数组
keepers,因此您可以只写for i in keepers....。那可能写成condition = Array.new(rand(1..4)).flat_map do |el| first = rand(1..20); [*first..first+rand(0..4)]; end.uniq # => [7, 8, 9, 18, 6]; keepers = [*1..20]-condition #=> [1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20]。我知道在其他情况下您需要在块内使用next if ....。