Concept Flow - Loop method for infinite loops
Start Loop
Execute Block
Repeat Automatically
↩Back to Start Loop
The loop method runs a block of code repeatedly without stopping, creating an infinite loop until manually stopped.
count = 1 loop do puts count count += 1 break if count > 3 end
| Step | count | Action | Output | Condition for break |
|---|---|---|---|---|
| 1 | 1 | Print count, increment count | 1 | count=2, not >3, continue |
| 2 | 2 | Print count, increment count | 2 | count=3, not >3, continue |
| 3 | 3 | Print count, increment count | 3 | count=4, >3, break loop |
| Exit | 4 | Loop ends due to break | count=4 > 3, loop stops |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| count | 1 | 2 | 3 | 4 | 4 |
Ruby's loop method runs a block endlessly. Use 'break' inside to stop the loop. Without break, loop runs forever. Syntax: loop do # code break if condition end
loop do; puts "Hello"; break; end do?loop do ... end creates an infinite loop that repeats the code inside.break immediately stops the loop after printing "Hello" once.loop method can take a block with curly braces or do...end.loop { puts "Hi" }, which is valid Ruby syntax for an infinite loop.count = 0 loop do puts count count += 1 break if count == 3 end
loop do:
loop do puts "Start" break puts "End" end
break stops the loop immediately when reached.puts "End" after break will never run because break exits the loop first.loop do method to repeatedly ask a user for input until they type "exit"?loop do method runs code repeatedly until broken.gets.chomp and break if input is "exit".Pass the test and this pattern moves unknown