# Variable that traverses the for is not updated

2

I am trying that when the `for` exterior% completes an iteration, the variable `i` is updated, in the way that is indicated in the `if` after the `for` internal ( `if i+self.nGroups > n` )

``````  for i in 0..n
for j in 0..self.nGroups-1
if i+j <= n
puts "i=#{i} , j=#{j}"
@competition_users[i+j].group = j+1
puts @competition_users[i+j].group
@competition_users[i+j].save
end
end
if  i+self.nGroups > n
i += 1
else
i += self.nGroups
end
end
``````

For the values `n=4` , `nGroups=2` , unfortunately the output of the `puts` is the following:

``````     i=0 , j=0
1
i=0 , j=1
2
i=1 , j=0
1
i=1 , j=1
2
i=2 , j=0
1
i=2 , j=1
2
i=3 , j=0
1
i=3 , j=1
2
i=4 , j=0
1
``````

When what I expect is:

``````     i=0 , j=0
1
i=0 , j=1
2
i=2 , j=0
1
i=2 , j=1
2
i=4 , j=0
1
``````

Basically, the `i` index does not change when I perform `i += self.nGroups`

Let's see if anyone can explain why it is, or if they can advise me to do it in another way. Thanks

asked by Jorge Vela Plaza 27.07.2017 в 20:49
source

0

The problem is that even if you write `i` within your if, it is overwritten to the value that follows the iteration, for example, consider this code:

``````for i in 0..3
puts "i (inicio): #{i}"
i += 2
puts "i (+2): #{i}\n\n"
end
``````

Result:

``````i (inicio): 0
i (+2): 2

i (inicio): 1
i (+2): 3

i (inicio): 2
i (+2): 4

i (inicio): 3
i (+2): 5
``````

You can see that `i` actually changes after adding `2` , however its value is assigned again the beginning of the iteration.

Therefore you must use a different variable to take control of the cycle.

source
1

I fixed it, since Ruby does not allow change in the loops `for` of its iterators, so there is no alternative but to change the structure for `while` . Therefore the code would be as follows:

`````` i = 0
while (i <= n)
for j in 0..self.nGroups-1
if i+j <= n
puts "i=#{i} , j=#{j}"
@competition_users[i+j].group = j+1
puts @competition_users[i+j].group
@competition_users[i+j].save
end
end
if  i+self.nGroups > n
i += 1
else
i += self.nGroups
end
end
``````

And the exit is the one commented:

``````          i=0 , j=0
1
i=0 , j=1
2
i=2 , j=0
1
i=2 , j=1
2
i=4 , j=0
1
``````