Ruby - While Loop

1. Introduction

In Ruby, loops allow you to repeatedly execute a block of code as long as a condition remains true. The while loop is one of the fundamental looping structures in Ruby. It continues to run a block of code as long as its condition evaluates to true. This guide will explore how to use the while loop effectively in Ruby.

2. Program Steps

1. Define a starting point or an initial value.

2. Specify a condition for the while loop. The loop will run as long as this condition remains true.

3. Inside the loop, write the code you want to execute repeatedly.

4. Update the value used in the condition to ensure the loop doesn't run indefinitely.

5. Once the condition becomes false, the program will exit the loop and proceed to the next line of code.

3. Code Program

# Define a starting point
count = 1
# Use the while loop
while count <= 5
  puts "Iteration number #{count}"
  count += 1
end

Output:

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

Explanation:

1. We start by defining a variable count with an initial value of 1.

2. The while loop checks the condition count <= 5. If it's true, the loop executes.

3. Inside the loop, the code puts "Iteration number #{count}" prints the current iteration number.

4. The line count += 1 increases the value of count by 1 with each iteration. This step ensures that our loop doesn't run indefinitely.

5. Once the count exceeds 5, the condition becomes false, causing the program to exit the loop.

The while loop provides a concise way to execute code multiple times based on a dynamic condition, making it a powerful tool in any Ruby developer's toolkit.


Comments