Shubham
Shubham

Reputation: 22317

How to modify loop variable in ruby?

for i in (0..5)
  if(i==0)
    i=4
  end
  puts i
end

In the above program I excepted the output as - 4 5

But instead it is - 4 1 2 3 4 5

So I conclude that loop variable isnt changing. How can change it? Can anyone tell me?

Actually, In my program I need to save the current state of loop and retrive later so that on the next start program resumes from the same point where it was left.

Upvotes: 1

Views: 4061

Answers (3)

Mladen Jablanović
Mladen Jablanović

Reputation: 44080

I am not sure how your code relates to the problem you are later mentioning. It looks to me that all you need to do is:

start_pos = load_start_pos || 0 # if not available for load, assume zero
(start_pos..end_pos).each do |i|
  if need_to_exit?
    save_start_pos i # save for later
    break # exit the loop
  end
end

Upvotes: 0

cletus
cletus

Reputation: 625077

The only way you'll be able to modify the loop variable is to use a while loop:

x = (2..7).to_a
i = 0
while (i < x.length)
  i = 4 if i == 0
  puts x[i]
  i = i + 1
end

Output:

6
7

In a for loop, as you've discovered, you can modify the loop variable and that value will hold for that iteration of the loop. On the next iteration, it will retrieve the next element from the range you specified so your modified value will essentially be overwritten.

Upvotes: 9

Adrian
Adrian

Reputation: 15171

There is no way to do that without a hack. The next best thing would be to use next.

x = (0..5).to_a
for i in (0..5)
  if(i < 4)
    next
  end
  puts x[i]
end

produces:

4
5

Upvotes: 3

Related Questions