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++

1

5 Answers 5

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
Sign up to request clarification or add additional context in comments.

Comments

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
}

Comments

2

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

Comments

1

Why not a recursive approach ? like

foo(x)
{
    if x == 7
    {
        return foo(9)
    }
    return foo(x+1)
}

Comments

1
(1..10).each do |i|
  next if(i == 7 || i == 8)
  # some code here
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.