1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

How to Use Loops in Ruby--While, Until, Each and Times Loops

Using Loops in Ruby

By

What Are Loops?

Computer programs often have to perform actions a number of times, not just once. For example, a program that prints all of your new email will need to print each email from a list, not just a single email. To do this, a constructs called loops are used. A loop will repeat the statements inside it a number of times until some condition is met.

While Loops

The first type of these loops is a while loop. While loops will execute all of the statements contained within them as long as the conditional statement remains true. In this example, the loop continually increases the value of the variable i by one. As long as the conditional statement i < 10 is true, the loop will continue executing the statement i += 1 which adds one to the variable.

#!/usr/bin/env ruby

i = 0
while i < 10
  i += 1
end

puts i

Until Loops

Until loops are almost identical to while loops except that they will loop as long as the conditional statement is false. The while loop will loop while the condition is true, the until loop will loop until the condition is true. This example is the functional equivalent of the while loop example, except using an until loop, until i == 10 . The variable is incremented by one until its value equals ten.

#!/usr/bin/env ruby

i = 0
until i == 10
  i += 1
end

puts i
  1. About.com
  2. Technology
  3. Ruby
  4. Beginning Ruby
  5. Ruby's Basic Features
  6. How to Use Loops in Ruby - While, Until, Each, Times Loops

©2014 About.com. All rights reserved.