This tutorial provides a comprehensive guide to Ruby’s loop control structures, including `while`, `until`, and `each`. You’ll learn how to use these loops effectively, understand their differences, and apply them to real-world scenarios. Each step builds on the previous one, with practical examples and engaging practice exercises.
Step 1: Introduction to Loops in Ruby
Loops are used to execute a block of code repeatedly. Ruby provides several loop structures, including while, until, and each. Understanding these loops is essential for writing efficient and readable code.
# Example of a simple loop
5.times do |i|
puts "Iteration #{i}"
endPractice Exercise
Write a loop that prints the numbers 1 to 10 using the times method.
Show Solution
10.times do |i|
puts i + 1
end
# Explanation: The `times` method iterates from 0 to 9, so we add 1 to `i` to print numbers 1 to 10.Step 2: The `while` Loop
The while loop executes a block of code as long as a condition is true. It's useful when the number of iterations is not known in advance.
# Example of a while loop
counter = 0
while counter < 5 do
puts "Counter: #{counter}"
counter += 1
endPractice Exercise
Write a while loop that simulates a countdown from 10 to 1, printing each number.
Show Solution
counter = 10
while counter >= 1 do
puts counter
counter -= 1
end
# Explanation: The loop continues as long as `counter` is greater than or equal to 1, decrementing `counter` each iteration.Step 3: The `until` Loop
The until loop is the opposite of while. It executes a block of code as long as a condition is false. Use it when you want to loop until a specific condition is met.
# Example of an until loop
counter = 0
until counter == 5 do
puts "Counter: #{counter}"
counter += 1
endPractice Exercise
Write an until loop that prints all even numbers between 0 and 10.
Show Solution
counter = 0
until counter > 10 do
puts counter if counter.even?
counter += 1
end
# Explanation: The loop continues until `counter` exceeds 10, printing only even numbers.Step 4: The `each` Method
The each method is used to iterate over collections like arrays and hashes. It's more idiomatic in Ruby than traditional loops and is preferred for iterating over known collections.
# Example of the each method
fruits = ['apple', 'banana', 'cherry']
fruits.each do |fruit|
puts "I love #{fruit}s!"
endPractice Exercise
Given an array of numbers [3, 7, 2, 9, 5], use the each method to print each number squared.
Show Solution
numbers = [3, 7, 2, 9, 5]
numbers.each do |num|
puts num ** 2
end
# Explanation: The `each` method iterates over the array, squaring each number and printing the result.Step 5: Combining Loops with Conditionals
Loops can be combined with conditionals to create more complex logic. For example, you can use if statements inside loops to filter or modify behavior based on conditions.
# Example of a loop with a conditional
numbers = [1, 2, 3, 4, 5]
numbers.each do |num|
if num.even?
puts "#{num} is even"
else
puts "#{num} is odd"
end
endPractice Exercise
Write a loop that iterates over an array of words and prints only those that start with the letter 'a'.
Show Solution
words = ['apple', 'banana', 'apricot', 'cherry', 'avocado']
words.each do |word|
puts word if word.start_with?('a')
end
# Explanation: The `each` method iterates over the array, and the `if` condition checks if the word starts with 'a'.Step 6: Nested Loops
Nested loops are loops within loops. They are useful for working with multi-dimensional data structures or performing repetitive tasks within repetitive tasks.
# Example of nested loops
(1..3).each do |i|
(1..3).each do |j|
puts "i: #{i}, j: #{j}"
end
endPractice Exercise
Write a nested loop that prints a multiplication table for numbers 1 to 5.
Show Solution
(1..5).each do |i|
(1..5).each do |j|
puts "#{i} * #{j} = #{i * j}"
end
end
# Explanation: The outer loop iterates through the first number, and the inner loop iterates through the second number, printing the product.Step 7: Breaking Out of Loops
Sometimes you need to exit a loop early. Ruby provides the break keyword to terminate a loop immediately.
# Example of breaking out of a loop
numbers = [1, 2, 3, 4, 5]
numbers.each do |num|
break if num > 3
puts num
endPractice Exercise
Write a loop that iterates over an array of numbers and stops when it encounters a number greater than 10.
Show Solution
numbers = [5, 8, 12, 3, 15]
numbers.each do |num|
break if num > 10
puts num
end
# Explanation: The loop stops when it encounters a number greater than 10, preventing further iterations.Step 8: Skipping Iterations with `next`
The next keyword allows you to skip the current iteration of a loop and move to the next one. It's useful for filtering out specific cases.
# Example of using next
numbers = [1, 2, 3, 4, 5]
numbers.each do |num|
next if num.even?
puts "#{num} is odd"
endPractice Exercise
Write a loop that prints only the odd numbers from an array, skipping even numbers using next.
Show Solution
numbers = [1, 2, 3, 4, 5, 6, 7]
numbers.each do |num|
next if num.even?
puts num
end
# Explanation: The `next` keyword skips even numbers, allowing only odd numbers to be printed.Step 9: Real-World Application: Processing User Input
Loops are often used to process user input until a specific condition is met. For example, you might repeatedly ask for input until the user provides a valid response.
# Example of processing user input
loop do
puts "Enter a number greater than 10:"
input = gets.chomp.to_i
break if input > 10
puts "Invalid input. Try again."
endPractice Exercise
Write a program that repeatedly asks the user for their age until they enter a valid age (between 1 and 120).
Show Solution
loop do
puts "Enter your age:"
age = gets.chomp.to_i
break if age.between?(1, 120)
puts "Invalid age. Please enter a number between 1 and 120."
end
# Explanation: The loop continues until the user enters a valid age within the specified range.Step 10: Advanced Challenge: Simulating a Game Loop
Loops are essential in game development for creating game loops that handle updates and rendering. Let's simulate a simple game loop.
# Example of a game loop
health = 100
while health > 0 do
puts "Health: #{health}"
damage = rand(1..20)
health -= damage
puts "You took #{damage} damage!"
end
puts "Game Over!"Practice Exercise
Create a game loop where the player starts with 50 health and gains 5 health every turn. The game ends when the player reaches 100 health.
Show Solution
health = 50
while health < 100 do
puts "Health: #{health}"
health += 5
puts "You gained 5 health!"
end
puts "You win!"
# Explanation: The loop continues until the player's health reaches 100, simulating a simple game mechanic.Sign in to take Cornell notes on this lesson — they save automatically and stay with your account.