如何在Ruby的循环中跳过几次迭代? [英] how to skip a few iterations in a loop in Ruby?
问题描述
假设我有下面的 C 代码
Suppose I have the C code below
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
跳过一次迭代,但我必须根据条件值跳过几次迭代,而且我不知道在运行前要跳过多少次迭代?
How to convert to Ruby? I know we can skip one iteration using next
, but I have to skip a few iterations depending on conditional value and I don't know how many iterations to skip before runtime?
这是我实际正在处理的代码(正如 Coreyward 提到的):
Here is the code I am actually working on (as mentioned by Coreyward):
我正在数组中寻找值差异小于 0.1 的直线"(小于 0.1 将被视为直线").范围必须大于 50 才能被视为长行".在我找到行范围 [a,b] 后,我想跳过迭代到上限 b,这样它就不会从 a+1 重新开始,它会从 b+1 开始寻找新的直线"
I am looking for "straight line" in the array that the values differs less than 0.1(less than 0.1 will considered as a "straight line"). The range has to be longer than 50 to be considered as a long "line". After I find the line range [a,b], i wanna skip the iterations to upper limit b so it would not start again from a+1, and it will start to find new "straight line" from 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
}
}
推荐答案
另一种方法是使用 枚举器 类:
Another way is using the enumerator class:
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>'
这篇关于如何在Ruby的循环中跳过几次迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!