How to skip multiple iterations in a loop in Ruby?

Suppose I have 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 } } 

How to convert to Ruby? I know that we can skip one iteration with next , but I need to skip several iterations depending on the conditional value, and I don't know how many iterations to skip before starting?


Here is the code I'm actually working on (as Coriward mentioned):

I am looking for a “straight line” in an array where values ​​differ less than 0.1 (less than 0.1 will be considered as a “straight line”). The range must be longer than 50 to be considered a long “line”. After I find the linear range [a, b], I want to skip the iterations to the upper limit of b so that it does not start again with + 1 and it starts looking for a 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 } 

}

+8
ruby
source share
2 answers

Another way is to use 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 

gives

 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>' 
+2
source share

Your case is not easily covered by typical ruby ​​iterators, but the ruby ​​also has regular loops that can completely cover c-for. the following is equivalent to your c loop above.

 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 
+3
source share

All Articles