break

You can use break to break out of a while loop:

  1. a = 2
  2. while (a += 1) < 20
  3. if a == 10
  4. break # goes to 'puts a'
  5. end
  6. end
  7. puts a # => 10

break can also take an argument which will then be the value that gets returned:

  1. def foo
  2. loop do
  3. break "bar"
  4. end
  5. end
  6. puts foo # => "bar"

If a break is used within more than one nested while loop, only the immediate enclosing loop is broken out of:

  1. while true
  2. pp "start1"
  3. while true
  4. pp "start2"
  5. break
  6. pp "end2"
  7. end
  8. pp "end1"
  9. break
  10. end
  11. # Output:
  12. # "start1"
  13. # "start2"
  14. # "end1"