Ruby Logo

Ruby Loops & Iterators

Master Ruby's looping constructs including while, until, for loops and the powerful each iterator with comprehensive examples and interactive practice.

Home Ruby Ruby Loops & Iterators

Ruby Loops & Iterators

Master Ruby's powerful looping constructs to repeat code execution efficiently. Learn when and how to use different types of loops and iterators for various programming scenarios.

What are Loops?

Loops: Programming constructs that allow you to execute a block of code repeatedly. They're essential for processing collections, automating repetitive tasks, and creating dynamic programs.

Real-World Analogy

Think of loops like a washing machine: You set it to run for a certain number of cycles (iterations), and it repeats the same process (wash, rinse, spin) until the condition is met (cycles complete). Your program does the same - it repeats code until a condition is satisfied.

while Loop

while: Executes a block of code repeatedly as long as a condition is true. Perfect for situations where you don't know exactly how many iterations you need.

Basic while Loop Structure

# Basic while loop structure
counter = 0

while
counter < 5
puts "Count: \#{counter}"
counter += 1
end

# Output: Count: 0, Count: 1, Count: 2, Count: 3, Count: 4

Practical while Loop Examples

# User input validation
user_input = nil
while
user_input.nil? || user_input.empty?
puts "Please enter your name:"
user_input = gets.chomp
end
puts
"Hello, \#{user_input}!"

# Processing until condition met
number = 1
while
number < 100
puts "Processing: \#{number}"
number *= 2
end
# Output: Processing: 1, Processing: 2, Processing: 4, Processing: 8, Processing: 16, Processing: 32, Processing: 64

⚠️ Avoiding Infinite Loops

  • Always modify the condition: Ensure the loop condition will eventually become false
  • Use break statements: Provide an escape mechanism for unexpected conditions
  • Test with small values first: Debug with limited iterations before running large loops
  • Consider timeout mechanisms: For long-running processes, implement time limits

until Loop

until: Ruby's unique loop that continues until a condition becomes true. It's the opposite of while - use it when you want to loop until something happens.

Basic until Loop Structure

# Basic until loop structure
countdown = 5

until
countdown == 0
puts "Countdown: \#{countdown}"
countdown -= 1
end
puts
"Blast off!"

# Output: Countdown: 5, Countdown: 4, Countdown: 3, Countdown: 2, Countdown: 1, Blast off!

Practical until Loop Examples

# Wait for file to be created
file_path = "data.txt"
until
File.exist?(file_path)
puts "Waiting for file to be created..."
sleep(1)
end
puts
"File found! Processing..."

# Retry until success
attempts = 0
success = false
until
success || attempts >= 3
attempts += 1
puts
"Attempt \#{attempts}"
# Simulate some operation
success = rand > 0.7
end
puts
success ? "Success!" : "Failed after 3 attempts"

for Loop

for: Traditional loop for iterating over ranges or collections. While available in Ruby, the each iterator is generally preferred for better readability and Ruby idioms.

Basic for Loop Structure

# for loop with range
for
i in 1..5
puts "Number: \#{i}"
end

# Output: Number: 1, Number: 2, Number: 3, Number: 4, Number: 5

# for loop with array
fruits = ["apple", "banana", "cherry"]
for
fruit in fruits
puts "I like \#{fruit}"
end

# Output: I like apple, I like banana, I like cherry

⚠️ Ruby Style Note

Prefer each over for: In Ruby, the each iterator is more idiomatic and preferred over for loops. It's more expressive, follows Ruby conventions, and integrates better with Ruby's object-oriented nature.

each Iterator (Ruby's Preferred Way)

each: Ruby's idiomatic way to iterate over collections. More expressive, readable, and Ruby-like than traditional for loops. This is the preferred method in Ruby.

Basic each Iterator Structure

# Basic each iterator
numbers = [1, 2, 3, 4, 5]

numbers.each
do
|num|
puts "Number: \#{num}"
end

# Output: Number: 1, Number: 2, Number: 3, Number: 4, Number: 5

Try It Yourself - Interactive Practice

Learning Tip: The best way to master loops is through hands-on practice! Try these examples and experiment with different loop types and conditions!

Interactive Code Runner

Ruby Code Editor
Output will appear here when you run the code...

Best Practices

Loop Best Practices

  • Prefer each over for: Use each iterator for collections - it's more Ruby-like
  • Avoid infinite loops: Always ensure your loop condition will eventually become false
  • Use meaningful variable names: Choose descriptive names for loop variables
  • Consider performance: Be mindful of loop efficiency, especially with large datasets
  • Test edge cases: Always test with empty collections and boundary conditions

Quick Navigation

Related Topics

Video Tutorial

Watch and learn ruby loops & iterators

Pro Tip: After reading through the content above, watch this video to reinforce your understanding and see the concepts in action!