Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 8 / 68

Loops (while statements)

In this lesson you will learn to repeat work with a while statement in Ruby, and how to tell it apart from each. This is for anyone searching for "Ruby while loop how to use".

while ... end repeats as long as the condition holds. The rule of thumb is to use each when you already know the stopping point and a while statement when you do not.

The sample code repeats while i is 5 or less, increasing the value by one with i += 1 inside the loop. The condition is evaluated at the top of every pass, and the moment it becomes false the loop exits.

A common stumbling block for beginners is forgetting to update the variable the condition depends on and ending up in an infinite loop. When you actually want one, the standard pattern is while true with a break to leave it.

It shines wherever the number of repetitions cannot be predicted, such as accepting user input continuously or searching until a condition is met. Since arrays are usually handled with each in Ruby, while tends to be used for more general situations.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)