Loops in Ruby allow you to execute a block of code multiple times, which is useful for tasks like iterating over collections or running repetitive tasks.
Ruby provides various loop constructs to handle different use cases.
What You’ll Learn
1. Introduction to Loops
Loops execute a block of code repeatedly until a condition is met or a specified number of iterations are completed. Ruby supports several looping mechanisms, making it versatile for various programming tasks.
2. The while Loop
The while loop executes code as long as a condition evaluates to true.
Syntax
while condition # code to execute end
Example
counter = 1 while counter <= 5 puts "Counter: #{counter}" counter += 1 end # Output: # Counter: 1 # Counter: 2 # Counter: 3 # Counter: 4 # Counter: 5
3. The until Loop
The until loop executes code until a condition evaluates to true.
Syntax
until condition # code to execute end
Example
counter = 1 until counter > 5 puts "Counter: #{counter}" counter += 1 end # Output is the same as the `while` example.
4. The for Loop
The for loop iterates over a range or collection.
Syntax
for variable in range_or_collection # code to execute end
Example: Iterating Over a Range
for num in 1..5 puts "Number: #{num}" end # Output: # Number: 1 # Number: 2 # Number: 3 # Number: 4 # Number: 5
Example: Iterating Over an Array
fruits = ["Apple", "Banana", "Cherry"] for fruit in fruits puts fruit end # Output: # Apple # Banana # Cherry
5. The each Loop
The each loop is commonly used to iterate over arrays, hashes, and other collections.
Example: Iterating Over an Array
fruits = ["Apple", "Banana", "Cherry"] fruits.each do |fruit| puts fruit end # Output: # Apple # Banana # Cherry
Example: Iterating Over a Hash
scores = { Alice: 90, Bob: 85, Carol: 95 } scores.each do |name, score| puts "#{name}: #{score}" end # Output: # Alice: 90 # Bob: 85 # Carol: 95
6. The times Loop
The times loop executes a block of code a specified number of times.
Syntax
number.times do # code to execute end
Example
5.times do |i| puts "Iteration: #{i + 1}" end # Output: # Iteration: 1 # Iteration: 2 # Iteration: 3 # Iteration: 4 # Iteration: 5
7. The loop Construct
The loop construct runs indefinitely until you explicitly break it.
Example
counter = 1 loop do puts "Counter: #{counter}" counter += 1 break if counter > 5 end # Output: # Counter: 1 # Counter: 2 # Counter: 3 # Counter: 4 # Counter: 5
8. Controlling Loops with break, next, and redo
8.1 break
Exits the loop immediately.
(1..10).each do |num| break if num > 5 puts num end # Output: # 1 # 2 # 3 # 4 # 5
8.2 next
Skips to the next iteration.
(1..5).each do |num| next if num == 3 puts num end # Output: # 1 # 2 # 4 # 5
8.3 redo
Restarts the current iteration.
count = 0 (1..5).each do |num| count += 1 redo if count == 2 puts num end # Note: Use `redo` carefully to avoid infinite loops.
9. Practical Examples
9.1 Summing Numbers
numbers = [1, 2, 3, 4, 5] sum = 0 numbers.each do |num| sum += num end puts "Sum: #{sum}" # Output: Sum: 15
9.2 Printing Even Numbers
(1..10).each do |num| next unless num.even? puts num end # Output: # 2 # 4 # 6 # 8 # 10
9.3 Generating Multiplication Table
(1..5).each do |i| (1..5).each do |j| print "#{i * j}\t" end puts end # Output: # 1 2 3 4 5 # 2 4 6 8 10 # 3 6 9 12 15 # 4 8 12 16 20 # 5 10 15 20 25
9.4 Loop with User Input
loop do print "Enter a number (or 'exit' to quit): " input = gets.chomp break if input == "exit" puts "You entered: #{input}" end # Output depends on user input.
9.5 Fibonacci Sequence
def fibonacci(n) a, b = 0, 1 n.times do puts a a, b = b, a + b end end fibonacci(10) # Output: # 0 # 1 # 1 # 2 # 3 # 5 # 8 # 13 # 21 # 34
10. Summary
Key Loop Constructs
- while: Loop while a condition is true.
- until: Loop until a condition is true.
- for: Iterate over ranges or collections.
- each: Iterate over arrays, hashes, or ranges.
- times: Repeat a block a specified number of times.
- loop: Infinite loop, explicitly terminated with break.
Best Practices
- Use each or times for iterating collections or fixed iterations for cleaner code.
- Avoid infinite loops unless necessary, and always include a break condition.
- Use next to skip iterations and redo sparingly to prevent infinite loops.
Mastering loops in Ruby allows you to handle repetitive tasks effectively and write concise, readable code