Ruby until Loop Tutorial

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

Note: we’re assuming you’re already familiar with the Ruby while loop.

What is until Loop in Ruby?

The until loop works just like the while loop, and it is used to run a block of code for as long as a condition is met.

But here’s the fundamental difference between the while and until loop:

  • The while loop works only if its condition results true!
  • But the until loop works only if its condition results false!

Basically, when using the until loop, our condition is like “as long as a condition is not met”.

Ruby until Loop Syntax:

until condition

#instructions within the body of the until loop

end

`until`: in order to create an until loop, we use the `until` keyword.

`condition`: this is the condition we define for the loop and if the result of the condition is false, then the body of the loop will run.

`end`: the `end` clause defines the closing border of the until statement’s block.

Example: using until loop in Ruby

num = 0

until num == 10

    num += 1

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

end

Output:

The value of the num varaible is: 1

The value of the num varaible is: 2

The value of the num varaible is: 3

The value of the num varaible is: 4

The value of the num varaible is: 5

The value of the num varaible is: 6

The value of the num varaible is: 7

The value of the num varaible is: 8

The value of the num varaible is: 9

The value of the num varaible is: 10

How does until loop work in Ruby?

In this example, the condition of the `until` loop is to check and see if the value of the `num` variable is equal to the value 10. Now, because the value of this variable is not equal to the value 10 at the moment (not until the next 10 iterations of the loop) so the result of the condition becomes false and so the body of the loop runs!

Now the moment the value of the `num` variable becomes 10, the result of the condition in the `until` loop will be true and so the loop breaks and the instructions after the loop will run (which in this example there’s none)

Difference between while loop and until loop in Ruby

The main difference is on the way they interpret their condition statement!

  • For while loop, as long as the condition of the while loop is true, the body of that loop will run.
  • But for the until loop, as long as the condition of the loop is FALSE, the body of that loop will run.
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies