Jamy
Jamy

Reputation: 115

How to exit `if` statement inside `for` loop

I'm looping over an array, and have an if statement inside.

[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

I want to print i if i == 4, and break, but still move on to the second if statement. How can I exit the if statement but not the for loop, still running the remaining code after the if block?

In my real scenario, I have a matrix:

  1     2     3     4     5 
  _     ♙     _     9     _ 
 11    12    13    14    15 
 16     _    18    19    20 
 21    22    23    24     _ 

Say my current pos is [1][1]. When I check my next element (row + i, col), I want to increment a value. But when I encounter '_' say [3][1], I should terminate from if statement.

Upvotes: 1

Views: 4482

Answers (3)

Axe
Axe

Reputation: 692

Maybe I am missing something. Unfortunately I am not entirely sure that I understand your question and the terminology that you use. The following makes sure that 'i > 6' does not have side-effects, in the same if block we perform the following check with elsif. Here you want the effect that you move onto the next item in the list, if I understand correctly. You can do that with 'next'.

[1,2,3,4,5,6,7,8,9].each do |i|
  if i > 6
    p i
  elsif i == 4
    p i
    next
  end
end

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230551

By "break from if", do you perhaps mean "interrupt execution of if's body"?

if condition
  puts 'doing something'
  # "break" here
  puts 'doing something else'
end

If so, it can be done like this:

catch(:break_from_if) do
  if condition
    puts 'doing something'
    throw :break_from_if
    puts 'doing something else'
  end
end

Note the verb: can be done, but shouldn't ever be done (in code that is of any importance)

Upvotes: 1

Schwern
Schwern

Reputation: 165586

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.

Remove the break.

There's no need to break out of if statements. They aren't loops. If the condition is true they run their block of code once and then continue onward.

this = 42

if this < 40
  p "less than 42"
end

if this > 40
  p "greater than 40"
end

p "after the ifs"

This will print.

"greater than 40"
"after the ifs"

Upvotes: 2

Related Questions