0
0
Rubyprogramming~5 mins

For loop (rarely used in Ruby)

Choose your learning style9 modes available
Introduction

A for loop repeats a set of actions for each item in a list. In Ruby, it's not used often because other ways are simpler.

When you want to do something with every item in a list, like printing each name.
When you have a fixed range of numbers and want to repeat actions for each number.
When you prefer a clear, simple loop structure instead of more Ruby-specific methods.
When learning basic programming loops before moving to Ruby's more common methods.
Syntax
Ruby
for variable in collection
  # code to run
end

The variable takes each item from the collection one by one.

The loop runs the code inside for ... end for every item.

Examples
This prints numbers 1 to 3, one per line.
Ruby
for i in 1..3
  puts i
end
This prints each fruit name from the list.
Ruby
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits
  puts fruit
end
Sample Program

This program prints a message for numbers 1 through 5 using a for loop.

Ruby
for number in 1..5
  puts "Number is #{number}"
end
OutputSuccess
Important Notes

Ruby developers usually prefer .each loops because they are more flexible and readable.

For loops work fine but are less common in Ruby code you see in real projects.

Summary

For loops repeat actions for each item in a list or range.

They are simple but not the usual way to loop in Ruby.

Use them when you want clear, straightforward looping syntax.