Loops are a core part of programming in Ruby. They let you repeat actions without rewriting code and they’re easier to use than they might seem at first! Here are a few common beginner questions I had when learning loops in Ruby during my Bootcamp.
What is the start and end of a loop in Ruby?
In Ruby, some loops are defined using a do ... end
block. This tells Ruby where the loop begins and ends.
🔍 Example:
7.times do
puts "There are 7 days in a week. Yes, 7."
end
✅ Output:
The loop executes the block exactly 7 times, once for each iteration (from 0 to 6), printing the message each time on its own line.
There are 7 days in a week. Yes, 7.
There are 7 days in a week. Yes, 7.
There are 7 days in a week. Yes, 7.
There are 7 days in a week. Yes, 7.
There are 7 days in a week. Yes, 7.
There are 7 days in a week. Yes, 7.
There are 7 days in a week. Yes, 7.
This loop runs the code inside the block 7 times. You can also use .each
, while
, and other loop styles that follow this same do ... end
structure.
What is an infinite loop in Ruby?
An infinite loop is a loop that never stops. It keeps running endlessly unless you include a break
statement or interrupt the program.
Example 1: Intentionally Infinite
while true
puts "This is a true loop"
end
This loop runs forever because the condition true
is always true.
Example 2: Accidental Infinite Loop
counter = 3
while counter < 100
puts counter # Oops! We forgot to increase counter, so this runs forever
end
In the second example, the loop condition is valid, but since counter
never changes, the loop never ends.
Pro Tip:
You can use break
inside a loop to manually stop it.
i = 0
while true
puts i
i += 1
break if i == 5
end
✅ Output:
0
1
2
3
4
💡 Why?
- The loop starts with
i = 0
- It prints
i
, then increases it by 1 (i += 1
) - The loop runs until
i == 5
, and then thebreak
exits the loop before printing5
So 0
through 4
get printed—but not 5. This loop prints numbers from 0
to 4
and then stops once i
hits 5
.
Did you create an infinite loop? Here’s how to stop it.
Ctrl + C
This sends an interrupt signal to the running Ruby script and stops the loop immediately. You can use this in Terminal (Mac, Linux, or Windows with WSL) or Windows Command Prompt.
Want to Learn More?
Check out my post on What break
does in Ruby loops, or explore Ruby conditionals for more beginner-friendly guidance.
✍️ Written During My Bootcamp
These are real questions I had while learning Ruby. I’m sharing them in case they’re helpful to you too!
Happy looping!