Ruby for Loop
Iterate over ranges and collections
📊 What is a for Loop?
The for loop in Ruby iterates over a range or collection. It's straightforward and familiar to programmers from other languages, though Ruby developers often prefer iterators like each.
# Basic 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 Variations
Range (Inclusive)
Iterate from start to end (includes end)
for i in 1..3
puts i
end
# Outputs: 1, 2, 3
Range (Exclusive)
Iterate from start to end (excludes end)
for i in 1...3
puts i
end
# Outputs: 1, 2
Array Iteration
Loop through array elements
for item in [1, 2, 3]
puts item
end
String Iteration
Loop through string characters
for char in "abc".chars
puts char
end
🔹 for Loop with Ranges
Ranges are the most common way to use for loops. Ruby has two types of ranges: inclusive (..) and exclusive (...).
# Inclusive range (includes 5)
puts "Inclusive range (1..5):"
for num in 1..5
puts num
end
# Exclusive range (excludes 5)
puts "\nExclusive range (1...5):"
for num in 1...5
puts num
end
Output:
Inclusive range (1..5): 1 2 3 4 5 Exclusive range (1...5): 1 2 3 4
🔹 for Loop with Arrays
You can iterate over arrays using for loops. Each element is accessed one at a time in the order they appear.
# Loop through array of strings
fruits = ["apple", "banana", "cherry"]
for fruit in fruits
puts "I like #{fruit}s"
end
# Loop through array of numbers
numbers = [10, 20, 30, 40]
sum = 0
for num in numbers
sum += num
end
puts "Total sum: #{sum}"
Output:
I like apples I like bananas I like cherrys Total sum: 100
🔹 Nested for Loops
You can nest for loops inside each other to work with multi-dimensional data or create patterns like multiplication tables.
# Simple multiplication table
for i in 1..3
for j in 1..3
print "#{i}x#{j}=#{i*j} "
end
puts # New line after each row
end
# Pattern printing
for row in 1..4
for col in 1..row
print "* "
end
puts
end
Output:
1x1=1 1x2=2 1x3=3 2x1=2 2x2=4 2x3=6 3x1=3 3x2=6 3x3=9 * * * * * * * * * *
🔹 for Loop with Strings
To iterate over characters in a string, you need to convert it to an array of characters using the .chars method:
# Iterate through string characters
word = "Ruby"
for letter in word.chars
puts "Letter: #{letter}"
end
# Count vowels in a string
text = "Hello World"
vowel_count = 0
for char in text.downcase.chars
if ['a', 'e', 'i', 'o', 'u'].include?(char)
vowel_count += 1
end
end
puts "Vowels found: #{vowel_count}"
Output:
Letter: R Letter: u Letter: b Letter: y Vowels found: 3
🔹 for Loop vs each Method
In Ruby, the each method is generally preferred over for loops. Here's a comparison to help you understand both approaches:
# Using for loop
puts "Using for loop:"
for i in 1..3
puts i
end
# Using each method (more Ruby-like)
puts "\nUsing each method:"
(1..3).each do |i|
puts i
end
# Both produce the same output!
# But 'each' is more idiomatic in Ruby
Output:
Using for loop: 1 2 3 Using each method: 1 2 3
Why Ruby developers prefer 'each':
- Scope: Variables in 'each' blocks are local to the block
- Functional style: 'each' fits Ruby's functional programming style better
- Chainable: You can chain other methods after 'each'
- Convention: It's the Ruby way and what most Rubyists expect
🔹 Practical for Loop Examples
Here are some real-world examples where for loops can be useful:
# Calculate factorial
n = 5
factorial = 1
for i in 1..n
factorial *= i
end
puts "Factorial of #{n} is #{factorial}"
# Generate a list of squares
squares = []
for num in 1..5
squares << num ** 2
end
puts "Squares: #{squares.join(', ')}"
# Process temperature readings
temperatures = [72, 75, 68, 80, 77]
for temp in temperatures
if temp > 75
puts "#{temp}°F - Hot!"
else
puts "#{temp}°F - Comfortable"
end
end
Output:
Factorial of 5 is 120 Squares: 1, 4, 9, 16, 25 72°F - Comfortable 75°F - Comfortable 68°F - Comfortable 80°F - Hot! 77°F - Hot!