Ruby - For Loop

1. Introduction

The for loop is a fundamental looping structure in Ruby, allowing developers to execute a block of code for a specific number of times, typically when iterating over a collection like an array or a range. This guide will dive into the usage of the for loop in Ruby.

2. Program Steps

1. Define the collection or range over which you want to iterate.

2. Use the for keyword followed by a variable that will represent the current item in each iteration.

3. Specify the collection or range you're iterating over.

4. Inside the loop, write the code you want to execute for each item.

5. Once the loop has iterated over every item in the collection or range, it will automatically exit.

3. Code Program

# Define a range
range = 1..5
# Use the for loop to iterate over the range
for number in range
  puts "Iteration for number #{number}"
end

Output:

Iteration for number 1
Iteration for number 2
Iteration for number 3
Iteration for number 4
Iteration for number 5

Explanation:

1. We start by defining a range that spans from 1 to 5.

2. The for loop is introduced with the keyword for followed by the variable number, which will represent the current item in each iteration.

3. We specify the collection we're iterating over, which in this case is the range we defined.

4. Inside the loop, the code puts "Iteration for number #{number}" is executed, printing the current iteration's number.

5. After the loop has processed each number in the range, it automatically exits, and the program continues.

The for loop is an efficient way to work through collections in Ruby and offers readability and ease of understanding, especially for those familiar with similar constructs in other programming languages.


Comments