A loop is the repetitive execution of a piece of code for a given amount of repetitions or until a certain condition is met. For instance, if a string is to be printed five times it can be done by typing five print statements; but, it is easier to set-up a loop to execute the same block of code five times.
The while statement executes a code repeatedly as long as the condition is true.
A while loop’s conditional is separated from the code by the reserved word
do
, a newline, a backslash (\
), or a semicolon.
while conditional [do]codeend
See the example below of how to write a while
loop in Ruby:
a = 1b = 6while a < b doprint a ,": Welcome to Educative.\n"a +=1end
begin
and end
can also be used to create a while loop.
begincodeend while [condition]
See the example below of how to write a begin
/end while
loop in Ruby:
x = 1beginprint x ,": Welcome to Educative.\n"x += 1end while x < 6
The until loop executes while the condition is false.
An until loop’s conditional is separated from the code by the reserved word
do
, a newline, backslash (\
), or a semicolon.
until conditional [do]codeend
See the example below of how to write an until
loop in Ruby:
x = 1y = 5until x > y doprint x ,": Welcome to Educative.\n"x +=1end
Like the while modifier, begin
and end
can also be used to create an until loop.
begincodeend until [condition]
See the example below of how to write a begin
/end until
loop in Ruby:
x = 1beginprint x ,": Welcome to Educative.\n"x += 1end until x > 5
The for loop consists of for
, followed by a variable to contain the iteration argument, followed by in
, and the value to iterate over using each
.
for variable [, variable ...] in expression [do]codeend
See the example below of how to write a for
loop in Ruby:
for x in 1..5print x ,": Welcome to Educative.\n"end
Free Resources