vendredi 26 octobre 2018

How to exit if statement inside for loop in Ruby?

I completely misunderstood the concept of unless or nextin ruby, and now I'm more puzzled.

Say I have an array that I'm looping; with an if statement inside. How can I exit the if statement, but not the for loop (this way the program can still run the remaining code after the if block.

For the sake of this question, I'm gonna use a dummy example to share my point.

[1,2,3,4,5,6,7,8,9].each do |i|

  if i == 4
    p i
    break
  end

  if i > 6
    p i
  end
end

What do I want?

In my code, I want to print out i if i == 4, and break. But still, move on to the second if statement.

I know that a simple fix is just to remove the break. But the main question is, how can I break from one if statement, and still go to the second if statement.

Aucun commentaire:

Enregistrer un commentaire