2

How to break double statement?

a = 1
b = 2
c = 3

if a == 1
    if b == 2
        c = 5
        d = 6
        break
    end
end

puts c
puts d

Output

loop.rb:9: Invalid break
loop.rb: compile error (SyntaxError)
Vyacheslav Loginov
  • 3,136
  • 5
  • 33
  • 49

1 Answers1

8

You can't break from inside an if, you can only break from inside loops and blocks.

If what you're asking is how to break from two nested loops, you can use catch in combination with throw—these are not the same as try and catch in other languages.

catch(:stop) do
  while some_cond
    while other_cond
      throw :stop
    end
  end
end

Of course, you can always just set a flag or some such to tell the outer loop that it should break too.

d11wtq
  • 34,788
  • 19
  • 120
  • 195