next

You can use next to try to execute the next iteration of a while loop. After executing next, the while‘s condition is checked and, if truthy, the body will be executed.

  1. a = 1
  2. while a < 5
  3. a += 1
  4. if a == 3
  5. next
  6. end
  7. puts a
  8. end
  9. # The above prints the numbers 2, 4 and 5

next can also be used to exit from a block, for example:

  1. def block
  2. yield
  3. end
  4. block do
  5. puts "hello"
  6. next
  7. puts "world"
  8. end
  9. # The above prints "hello"

Similar to break, next can also take a parameter which will then be returned by yield.

  1. def block
  2. puts yield
  3. end
  4. block do
  5. next "hello"
  6. end
  7. # The above prints "hello"