0
0
Rubyprogramming~5 mins

While loop in Ruby

Choose your learning style9 modes available
Introduction

A while loop helps you repeat a set of actions as long as a condition is true. It saves time by avoiding writing the same code again and again.

When you want to keep asking a user for input until they give a valid answer.
When you want to count up or down until a certain number is reached.
When you want to keep checking if a task is done before moving on.
When you want to repeat an action until something changes in your program.
Syntax
Ruby
while condition
  # code to repeat
end

The condition is checked before each loop. If it is true, the code inside runs.

When the condition becomes false, the loop stops.

Examples
This prints numbers 1 to 3 by increasing i each time.
Ruby
i = 1
while i <= 3
  puts i
  i += 1
end
This counts down from 5 to 1, printing each number.
Ruby
count = 5
while count > 0
  puts "Countdown: #{count}"
  count -= 1
end
Sample Program

This program prints numbers from 1 to 5 using a while loop.

Ruby
number = 1
while number <= 5
  puts "Number is #{number}"
  number += 1
end
OutputSuccess
Important Notes

Be careful to change something inside the loop so the condition eventually becomes false. Otherwise, the loop will run forever.

You can use break inside the loop to stop it early if needed.

Summary

A while loop repeats code as long as a condition is true.

It checks the condition before each repetition.

Make sure the condition will become false to avoid infinite loops.