How to Use For Loop in Ruby: Syntax and Examples
for loop repeats code for each item in a range or collection. Use for variable in collection followed by the code block and end to loop through elements.Syntax
The for loop in Ruby iterates over a range or collection. It starts with for variable in collection, runs the code inside the loop for each item, and ends with end.
- variable: holds the current item in each loop cycle.
- collection: a range, array, or any enumerable object.
- end: marks the end of the loop block.
for variable in collection
# code to run
endExample
This example shows a for loop that prints numbers from 1 to 5. It demonstrates how the loop runs the code block for each number in the range.
for i in 1..5 puts "Number: #{i}" end
Common Pitfalls
One common mistake is forgetting the end keyword, which causes a syntax error. Another is using a variable name that conflicts with existing variables, which can cause unexpected results.
Also, Rubyists often prefer each method over for loops because each creates a new scope for variables, avoiding side effects.
wrong: for i in 1..3 puts i # missing end causes error right: for i in 1..3 puts i end
Quick Reference
Use for loops to iterate over ranges or arrays simply. Remember to close the loop with end. For better variable scope control, consider using each method.
| Concept | Description |
|---|---|
| for variable in collection | Starts the loop over each item in collection |
| end | Ends the loop block |
| variable | Holds current item in each iteration |
| collection | Range, array, or enumerable to loop over |
Key Takeaways
for variable in collection and end to create a for loop in Ruby.end to close the loop and avoid syntax errors.each for better variable scope and Ruby style.