如何在Ruby的循环中跳过几次迭代?

时间:2012-03-29 18:02:07

标签: ruby

假设我有以下C代码

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?我知道我们可以使用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 个答案:

答案 0 :(得分:3)

典型的ruby迭代器不容易覆盖你的情况,但ruby也有普通的while循环,它可以完全覆盖c-for。以下等同于上面的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

答案 1 :(得分: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>'