2012-03-29 63 views
8

假设我有以下如何跳过Ruby中的循环中的几个迭代?

for(i = 0; i < 10; i++){ 
    printf("Hello"); 
    if(i == 5){ 
     a[3] = a[2] * 2; 
     if(a[3] == b) 
      i = a[3];   //Skip to index = a[3]; depends on runtime value 
    } 
} 

如何转换到Ruby的C代码?我知道我们可以使用next跳过一次迭代,但是我必须根据条件值跳过几次迭代,并且我不知道在运行前要跳过多少次迭代?


这里是我实际工作于(如由Coreyward提及)的代码:我寻找阵列中“直线”的数值相差小于0.1(小于0.1将

视为“直线”)。该范围必须长于50才能被视为长“线”。找到行范围[a,b]后,我想跳过迭代到上限b,所以它不会再从+ 1开始,它会开始从b + 1中找到新的“直线”。

for(i=0; i<arr.Length; i++){ 
    if(arr[i] - arr[i + 50] < 0.1){ 
    m = i;         //m is the starting point 
    for(j=i; j<arr.Length; j++){    //this loop makes sure all values differs less than 0.1 
     if(arr[i] - arr[j] < 0.1){ 
     n = j; 
     }else{ 
     break; 
     } 
    } 
    if(n - m > 50){       //Found a line with range greater than 50, and store the starting point to line array 
     line[i] = m 
    } 
    i = n          //Start new search from n 
    } 

}

+2

这将是大有帮助,如果你提供你想要达到什么目的。在Enumerator类中有一些非常方便的方法可以让你设置下一次迭代的值('feed')并查看下一个值('peek'),并且你还可以使用for循环红宝石。我确信有一个更清晰的写作方式,我只是不知道它在做什么。 – coreyward 2012-03-29 18:09:29

+0

你要在C中索引数组的末尾,可能想要将边界改为'arr.Length-50'。这似乎是一个有点复杂的方式来找到50个或更多的价值与初始值的epsilon运行。 – dbenhur 2012-03-29 18:48:25

+0

您似乎认为较大指数的值永远不会低于指数较低的值。这是真的? – dbenhur 2012-03-29 18:52:25

回答

2

另一种方法是使用enumerator类:

iter = (1..10).to_enum 
while true 
    value = iter.next 
    puts "value is #{value.inspect}" 
    if value == 5 
    3.times {value = iter.next} 
    end 
end 

value is 1 
value is 2 
value is 3 
value is 4 
value is 5 
value is 9 
value is 10 
StopIteration: iteration reached at end 
     from (irb):15:in `next' 
     from (irb):15 
     from C:/Ruby19/bin/irb:12:in `<main>' 
+0

这很可爱,但并不等同于直接推进索引。如果用i遍历一个数组并且达到了想要前进到索引j的决定,那么执行'(j-i).times {iter.next}'比分配'i = j'更加复杂和昂贵。 – dbenhur 2012-04-03 16:28:19

3

你的情况下,不容易被典型红宝石迭代器覆盖,但Ruby也有普通的,同时它可以完全覆盖环C-的。以下相当于上面的c for循环。

i = 0; 
while i < 10 
    puts "Hello" 
    if i == 5 
    a[3] = a[2] * 2 
    i = a[3] if a[3] == b 
    end 
    # in your code above, the for increment i++ will execute after assigning new i, 
    # though the comment "Skip to index = a[3]" indicates that may not be your intent 
    i += 1 
end 
+0

是的,这有效,但有没有办法与统计员做到这一点?我在考虑'drop',因此它会将值降到5和a [3]之间,但是当我开始编码时会感到困惑和迷茫。 – texasbruce 2012-03-29 18:31:21