Holla Tech - Learn

Loops
 

Loops are used to execute the same block of code a specified number of times.
The while loop executes a block of code while its condition is true.
For example: 

x = 0
while x < 10
  puts x
  x += 1
end 

 

This will output the numbers 0 to 9. After the loop control variable becomes 10, the condition x < 10 evaluates to false and the loop ends its execution.

NOTE!
If we leave out the x+=1 statement, the loop will run forever, because the condition will remain true. This situation is called an infinite loop.

until Loops
 

The until loop is the opposite of a while loop: it will run while its condition is false.
For example:

a = 0
until a > 10
  puts “a = #{a}”
  a +=2
end 

 

NOTE!
This will print all even numbers from 0 to 10.

BACK NEXT

CLICK ON THE BUTTON BELOW TO GO TO THE RUBY MAIN COURSE PAGE. 

RUBY MAIN COURSE PAGE

 


© License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT