Ruby while Loop
Execute code while a condition is true
⏰ What is a while Loop?
The while loop executes code repeatedly as long as a condition remains true. It checks the condition before each iteration, making it perfect for unknown repetition counts.
# Basic while loop
count = 1
while count <= 3
puts "Count: #{count}"
count += 1
end
Output:
Count: 1 Count: 2 Count: 3
while Loop Syntax
Basic Syntax
Standard while loop structure
while condition
# code block
end
Condition Check
Evaluated before each iteration
x = 0
while x < 5
puts x
x += 1
end
Increment
Update variable to avoid infinite loop
i = 1
while i <= 3
puts i
i += 1 # Important!
end
One-line Form
Compact syntax for simple loops
i = 0
puts i += 1 while i < 3
🔹 Basic while Loop
The while loop continues executing as long as the condition evaluates to true. Always remember to update the condition variable to prevent infinite loops.
# Print numbers 1 to 5
number = 1
while number <= 5
puts "Number: #{number}"
number += 1
end
puts "Loop finished!"
Output:
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 Loop finished!
🔹 while Loop with Conditions
You can use various conditions in while loops, including comparisons, boolean values, and method calls that return true or false.
# Loop with comparison
temperature = 15
while temperature < 20
puts "Temperature: #{temperature}°C - Too cold!"
temperature += 2
end
puts "Temperature: #{temperature}°C - Perfect!"
# Loop with boolean
running = true
count = 0
while running
count += 1
puts "Running... #{count}"
running = false if count >= 3
end
Output:
Temperature: 15°C - Too cold! Temperature: 17°C - Too cold! Temperature: 19°C - Too cold! Temperature: 21°C - Perfect! Running... 1 Running... 2 Running... 3
🔹 Nested while Loops
You can place one while loop inside another to create nested loops. This is useful for working with multi-dimensional data or creating patterns.
# Multiplication table
i = 1
while i <= 3
j = 1
while j <= 3
print "#{i}x#{j}=#{i*j} "
j += 1
end
puts # New line
i += 1
end
Output:
1x1=1 1x2=2 1x3=3 2x1=2 2x2=4 2x3=6 3x1=3 3x2=6 3x3=9
🔹 Common while Loop Patterns
Here are some frequently used patterns with while loops that you'll encounter in real programming:
# Countdown
countdown = 5
while countdown > 0
puts countdown
countdown -= 1
end
puts "Go!"
# Sum calculation
sum = 0
num = 1
while num <= 5
sum += num
num += 1
end
puts "Sum of 1 to 5: #{sum}"
# User input simulation (with counter)
attempts = 0
max_attempts = 3
while attempts < max_attempts
puts "Attempt #{attempts + 1}"
attempts += 1
end
Output:
5 4 3 2 1 Go! Sum of 1 to 5: 15 Attempt 1 Attempt 2 Attempt 3
🔹 while Loop Best Practices
Follow these guidelines to write effective and safe while loops:
Important Tips:
- Always update the condition: Make sure the loop variable changes to avoid infinite loops
- Initialize before the loop: Set your counter or condition variable before the while statement
- Keep conditions simple: Complex conditions make code harder to understand
- Use meaningful variable names: Use names like 'count' or 'index' instead of 'i' or 'x'
- Consider alternatives: Sometimes .times or .each methods are clearer than while loops
# Good practice
counter = 0
while counter < 5
puts "Iteration #{counter}"
counter += 1 # Don't forget this!
end
# Avoid infinite loops!
# BAD: This will run forever
# x = 0
# while x < 5
# puts x
# # Missing: x += 1
# end