Skip to content

while

A while executes its body as long as its condition is truthy.

while some_condition
  do_this
end

The condition is first tested and, if truthy, the body is executed. That is, the body might never be executed.

A while's type is always Nil.

Similar to an if, if a while's condition is a variable, the variable is guaranteed to not be nil inside the body. If the condition is an var.is_a?(Type) test, var is guaranteed to be of type Type inside the body. And if the condition is a var.responds_to?(:method), var is guaranteed to be of a type that responds to that method.

The type of a variable after a while depends on the type it had before the while and the type it had before leaving the while's body:

a = 1
while some_condition
  # a : Int32 | String
  a = "hello"
  # a : String
  a.size
end
# a : Int32 | String

Checking the condition at the end of a loop

If you need to execute the body at least once and then check for a breaking condition, you can do this:

while true
  do_something
  break if some_condition
end

Or use loop, found in the standard library:

loop do
  do_something
  break if some_condition
end

break

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

a = 2
while (a += 1) < 20
  if a == 10
    break # goes to 'puts a'
  end
end
puts a # => 10

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

def foo
  loop do
    break "bar"
  end
end

puts foo # => "bar"

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.

a = 1
while a < 5
  a += 1
  if a == 3
    next
  end
  puts a
end

# The above prints the numbers 2, 4 and 5

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

def block
  yield
end

block do
  puts "hello"
  next
  puts "world"
end

# The above prints "hello"

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

def block
  puts yield
end

block do
  next "hello"
end

# The above prints "hello"

until

An until executes its body until its condition is truthy. An until is just syntax sugar for a while with the condition negated:

until some_condition
  do_this
end

# The above is the same as:
while !some_condition
  do_this
end

break and next can also be used inside an until.