Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Kernel#loop

() { () -> void } -> bot
() -> ::Enumerator[nil, bot]
loop { block }
loop → an_enumerator

Repeatedly executes the block.

If no block is given, an enumerator is returned instead.

Example
loop do
  print "Input: "
  line = gets
  break if !line or line =~ /^q/i
  # ...
end

A StopIteration raised in the block breaks the loop. In this case, loop returns the “result” value stored in the exception.

Example
enum = Enumerator.new { |y|
  y << "one"
  y << "two"
  :ok
}

result = loop {
  puts enum.next
} #=> :ok
See also #local_variables #__method__ #load #open also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0