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
}
}
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?
Here is the code I am actually working on (as mentioned by Coreyward):
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
}
}
In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.
Exiting A Method Ruby methods end naturally on their last line of code. Use the return keyword.
The each() is an inbuilt method in Ruby iterates over every element in the range. Parameters: The function accepts a block which specifies the way in which the elements are iterated. Return Value: It returns every elements in the range.
Your case isn't easily covered by typical ruby iterators, but ruby also has ordinary while loops which can completely cover c-for. the following is equivalent to your c for 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With