Ruby while Loop Tutorial

In this section, we will learn what the while loop is and how to use it in Ruby.

The while Loop in Ruby

The while loop is used to run a set of instructions (a block of code) for as long as a condition is true.

Basically, a while loop is a combination of a condition statement and a block where we put instructions to be run.

Now the condition of the while loop first is checked and if that condition was true, then the body of the loop will run as a result. After the execution of the block, the condition is checked again and if it results true, the body of the while loop will run again.

This process keeps going on until the condition of the while loop results false and, in that case, the loop breaks and the instructions after the while loop continues to run.

Ruby while Loop Syntax

while condition

end

`while`: in order to create a while loop we start with the keyword `while`.

`condition`: this is the expression we define for this while loop to be checked every time the body of the loop runs. Note that for the first time, the condition is first checked and if the result was true, in that case only the body will run. This means there’s a chance that the body might not get a chance of running (if the condition of the while loop was false in the first place).

`end`: after the condition of the while loop, the lines below it represent the body of the while loop until the `end` clause, where it represents the closing border of the loop.

Example: using while loop in Ruby

puts "Please enter a value"

val = gets.chomp

while val != "end"

    puts "The value you've entered is: #{val}"

    puts "Please enter a value or the word 'end' if you want to terminate the program"

    val = gets.chomp

end

puts "The program is finished. "

Output:

Please enter a value

jack

The value you've entered is: jack

Please enter a value or the word 'end' if you want to terminate the program

John

The value you've entered is: John

Please enter a value or the word 'end' if you want to terminate the program

end

The program is finished.

How does while loop work in Ruby?

In this example, the condition of the while loop is to check the value of the `val` variable and see if it’s equal to the value `end`. So as long as the value of the `val` variable is not equal to the value `end` that means the condition of the while loop is true and so its body will run over and over again.

Note: every time the body of the loop runs, the condition of the loop will be checked again. For this reason, it is recommended to design the body of the loop in a way that modifies the condition of the loop so that at a certain point in the future, the loop breaks. This will stop the loop from running forever!

How to Exit while loop in Ruby?

Usually, a loop will run as long as its condition is true. So in a typical form, we should design the body of the loop in a way that affects the condition so that at a certain point, that loop’s condition becomes false in order to terminate the work of the loop.

But there’s another way of terminating a while loop (AKA breaking a loop) and that is using the `break` statement.

Basically, using the `break` statement, we can break the loop even when the condition of that loop is still true!

Example: using the break statement in while loop

num = 0

while num <10

    if num == 5

        break

    end

    puts "The value fo the num variable is: #{num}"

    num += 1

end

puts "The program is finished. "

Output:

The value of the num variable is: 0

The value of the num variable is: 1

The value of the num variable is: 2

The value of the num variable is: 3

The value of the num variable is: 4

The program is finished.

As you can see, the condition of the loop is to run for 10 times but within the body of the while loop we’ve used the if statement to check when the num variable reaches the value 5. In that point the if statement runs a call to the break statement and that will cause the loop to break (terminate its work). That’s why after 5 iterations, the loop terminated and the instructions after the loop ran.

Ruby while loop and next statement

When working with the while loop, sometimes we want to stop the current iteration of the loop and move on to the next one! For example, let’s say using the while loop we’re iterating through a sequence of numbers and want to jump over the value 30 when it appeared and move on to the value 31 without running the body of the loop for the value 30.

This is where we can use the `next` statement!

Note: For those of you who’re coming from C-Related languages, the next statement is equal to the `continue` statement.

Example: using next statement in while loop

num = 0

while num <10
    num += 1
    if num <= 5
        next 
    end 
    puts "The value fo the num variable is: #{num}"
    
end

puts "The program is finished. "

Output:

The value of the num variable is: 6

The value of the num variable is: 7

The value of the num variable is: 8

The value of the num variable is: 9

The value of the num variable is: 10

The program is finished.

In the body of the while loop, we have the if statement where it checks the value of the `num` variable and for as long as the value is less than 5 it will call the `next` statement. And because of this call, the rest of instructions in the while loop will be skipped and the program jumps into the next iteration of the loop. This call to the `next` statement happened for 5 times and so we didn’t get the first 5 numbers in the output stream.

Ruby Infinite while loop

In the examples you’ve seen so far, we’ve designed the instructions within the body of the while loop in a way that it affected the condition of the loop so at certain point, the condition resulted false and the loop terminated, eventually.

But sometimes we might want to run the loop forever or basically for as long as our computer allows it (because computers sometimes automatically stop a program if it’s taking too much resource and causes harm to the hardware).

So if the purpose is to create an infinite loop, the simplest method of doing so is to put the value `true` or a truthy value as the condition of the while loop.

Note: be very cautious when attempting to create an infinite loop! Because, as the name suggests, the moment your program enters an infinite loop, it will stay there for as long as your program is running. So no code after the while loop will run anymore.

Usually it’s rare you want to create a program with an infinite while loop! But if you needed, try to put a break point trigger in your program in case of an emergency.

Example: creating infinite while loop in Ruby

num = 0

while true
    num += 1

    if num ==100
        break
    end 
    
end

puts "The value of the num variable is: #{num} "

Output:

The value of the num variable is: 100

In this example, the condition of the while loop is set to `true` and so it means the condition of the while loop will never result to false!

So in this little program, in order to stop the loop at some point, we decided to break the loop using the break statement when the value of the `num` variable reached to 100.

More to Read:

Ruby for loop Statement

Ruby break Statement

Ruby next Statement

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies