instance method
Kernel#loop
() { () -> void } -> bot
() -> ::Enumerator[nil, bot]
loop { block }
loop → an_enumerator
kernel.rb
View on GitHub ↗
# File tmp/rubies/ruby-4.0.0/kernel.rb, line 161
def loop
Primitive.attr! :inline_block
unless defined?(yield)
return Primitive.cexpr! 'SIZED_ENUMERATOR(self, 0, 0, rb_f_loop_size)'
end
begin
while true
yield
end
rescue StopIteration => e
e.result
end
end
Repeatedly executes the block.
If no block is given, an enumerator is returned instead.
Example
loop do print "Input: " line = gets # break if q, Q is entered or EOF signal (Ctrl-D on Unix, Ctrl-Z on windows) is sent 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