Ruby Loops

Repeating code execution with loops

🔁 What are Ruby Loops?

Loops in Ruby allow you to execute a block of code multiple times. They help automate repetitive tasks and make your code more efficient and cleaner.


# Simple loop example
5.times do
  puts "Hello, Ruby!"
end
                                    

Output:

Hello, Ruby!
Hello, Ruby!
Hello, Ruby!
Hello, Ruby!
Hello, Ruby!

Types of Ruby Loops

while Loop

Repeats while condition is true

i = 0
while i < 3
  puts i
  i += 1
end
🔄

until Loop

Repeats until condition becomes true

i = 0
until i == 3
  puts i
  i += 1
end
📊

for Loop

Iterates over a range or collection

for i in 1..3
  puts i
end
🎯

Iterators

Ruby's elegant way to loop

[1, 2, 3].each do |num|
  puts num
end

🔹 The times Method

The times method is the simplest way to repeat code a specific number of times. It's perfect for beginners and makes your code very readable.

# Print numbers 0 to 4
5.times do |i|
  puts "Number: #{i}"
end

# Without block variable
3.times do
  puts "Ruby is fun!"
end

Output:

Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
Ruby is fun!
Ruby is fun!
Ruby is fun!

🔹 The loop Method

The loop method creates an infinite loop that continues until you explicitly break out of it using the break keyword.

# Infinite loop with break
count = 0
loop do
  puts "Count: #{count}"
  count += 1
  break if count >= 3
end

Output:

Count: 0
Count: 1
Count: 2

🔹 Choosing the Right Loop

Different loops work best for different situations. Here's a quick guide to help you choose:

When to Use Each Loop:

  • times: When you know exactly how many times to repeat
  • while: When you repeat while a condition is true
  • until: When you repeat until a condition becomes true
  • for: When iterating over a range or collection
  • each: When working with arrays or collections (most Ruby-like)
  • loop: When you need an infinite loop with custom break conditions

🔹 Practical Loop Examples

Here are some real-world examples of using loops in Ruby:

# Countdown timer
5.downto(1) do |i|
  puts "#{i}..."
end
puts "Blast off!"

# Sum of numbers
sum = 0
1.upto(5) do |i|
  sum += i
end
puts "Sum: #{sum}"

Output:

5...
4...
3...
2...
1...
Blast off!
Sum: 15

🧠 Test Your Knowledge

Which loop is best for repeating code exactly 10 times?