Change index variable inside ruby ​​loop

I understand that this may be against the ruby ​​principle and may seem a little silly, but I'm curious if it is possible to change the index variable during iteration of the loop in ruby.

This practice is possible in Java / C with a for loop in this contrived example:

for (int k = 0; k < 10; k++) { if (k == 5) k = 8; } 

In addition, I know that you can access an index variable with Enumerable # each_with_index, but I'm interested in the ability to change the variable in this instance, rather than accessing it.

+4
source share
3 answers

actually for semantics the following:

 for(executed_once_before_all; test; execute_every_loop) { /* code */ } 

and so in ruby:

 executed_once_before_all while test do execute_every_loop # code end 

so your example looks like this:

 k = 0 while k < 10 do k += 1 k = 8 if (k == 5) end 
+4
source

Changing the for loop counter in Ruby does not change the number of iterations.

You can change the counter variable, but this will only affect the current iteration:

 > for k in 0...10 > k = 8 if k == 5 > puts k > end 0 1 2 3 4 8 # Note this! 6 7 8 9 

The best way to achieve the desired behavior is to use the while suggested by @fotanus.

Of course, you can do this with a for loop using next statements, but this is much more ugly:

 for k in 0...10 next if k > 5 && k <= 8 ... do stuff ... next if k == 5 ... do stuff ... end 
0
source

You can do this, but Ruby programmers usually do not use a for loop (although it is available). You can also do something like this:

 [0,1,2,3,4,5,8,9,10].each do |index| # your code here end 
-2
source

Source: https://habr.com/ru/post/1484948/


All Articles