1

How can i achieve something like this in for loop in ruby:

for(int i = 1;i<=10;i++){
        if (i == 7){
            i=9;
        }
        #some code here
    }

I meant to say it's okay to use "next" to skip but what to do if I want to just jump to an uncertain iteration via changing the variable value itself. As far as I know loop works with enumerable type. I want to loop it via index as a variable, the way we do in C++

Uchiha_itachi
  • 103
  • 1
  • 2
  • 13
  • possible duplicate of [Syntax for a for loop in ruby](http://stackoverflow.com/questions/2032875/syntax-for-a-for-loop-in-ruby) – Pak Jun 02 '15 at 14:18

5 Answers5

3

There are few things you can do:

Incase you want to skip a few iterations based on a defined logic, you can use:

next if condition

If your intention is to randomly iterate over the whole range, you can try this:

(1..10).to_a.shuffle.each { |i| 
   # your code
}

Incase you want to randomly iterate over a certain chunk of given range, try this:

(1..10).to_a.shuffle.first(n).each { |i| # n is any number within 1 to 10
  # your code
}
shivam
  • 16,048
  • 3
  • 56
  • 71
3

The most accurate answer to your question would be to use a while loop, like this:

i = 0
while i < 10
  if i == 0 # some condition
    i = 9 # skip indexes
  else
    i += 1 # or not
  end
end
Piotr Kruczek
  • 2,384
  • 11
  • 18
1

Why not a recursive approach ? like

foo(x)
{
    if x == 7
    {
        return foo(9)
    }
    return foo(x+1)
}
shivam
  • 16,048
  • 3
  • 56
  • 71
Arkantus
  • 120
  • 1
  • 10
1
(1..10).each do |i|
  next if(i == 7 || i == 8)
  # some code here
end
msergeant
  • 4,771
  • 3
  • 25
  • 26
1

How about this?

array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

array.each_with_index do |elem, idx|
    break if idx == 9
    # do something
    puts "element #{idx} with #{elem}"
end
Roger
  • 7,535
  • 5
  • 41
  • 63