Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I realize this may be against ruby principle and may seem a bit silly, but I am curious to whether it possible to modify the index variable during iteration of a loop in ruby.

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

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

As well, I am aware that it is possible to access an index variable with Enumerable#each_with_index, but I am interested with the ability to alter the variable in this instance rather than access it.

share|improve this question
5  
Why do you want to do this? –  squiguy Jun 7 '13 at 2:31
    
As fotanus said -- it is possible to mimic this code in ruby, but I can't imagine any real problem that would be solved this way. –  samuil Jun 7 '13 at 8:07
add comment

3 Answers

actually the for semantic is 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 exemple is like this:

k = 0
while k < 10 do
  k += 1
  k = 8 if (k == 5)
end         
share|improve this answer
add comment

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

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

> 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 behaviour is to use while loop as @fotanus suggested.

Of course, you can do that with for loop using next statements, but that's much more ugly:

for k in 0...10
  next if k > 5 && k <= 8
  ... do stuff ...
  next if k == 5
  ... do stuff ...
end
share|improve this answer
add comment

You could do that, but Ruby programmers generally don't use the for loop (although it's available). You could also do something like this:

[0,1,2,3,4,5,8,9,10].each do |index|
  # your code here
end
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.