0
0
RubyHow-ToBeginner · 3 min read

How to Use For Loop in Ruby: Syntax and Examples

In Ruby, a 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.
ruby
for variable in collection
  # code to run
end
💻

Example

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.

ruby
for i in 1..5
  puts "Number: #{i}"
end
Output
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5
⚠️

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.

ruby
wrong:
for i in 1..3
  puts i
# missing end causes error

right:
for i in 1..3
  puts i
end
Output
1 2 3
📊

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.

ConceptDescription
for variable in collectionStarts the loop over each item in collection
endEnds the loop block
variableHolds current item in each iteration
collectionRange, array, or enumerable to loop over

Key Takeaways

Use for variable in collection and end to create a for loop in Ruby.
The loop runs the code block once for each item in the collection or range.
Always include end to close the loop and avoid syntax errors.
Consider using each for better variable scope and Ruby style.
For loops work well with ranges and arrays to repeat actions easily.