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] code end
See the example below of how to write a while
loop in Ruby:
a = 1 b = 6 while a < b do print a ,": Welcome to Educative.\n" a +=1 end
begin
and end
can also be used to create a while loop.
begin code end while [condition]
See the example below of how to write a begin
/end while
loop in Ruby:
x = 1 begin print x ,": Welcome to Educative.\n" x += 1 end 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] code end
See the example below of how to write an until
loop in Ruby:
x = 1 y = 5 until x > y do print x ,": Welcome to Educative.\n" x +=1 end
Like the while modifier, begin
and end
can also be used to create an until loop.
begin code end until [condition]
See the example below of how to write a begin
/end until
loop in Ruby:
x = 1 begin print x ,": Welcome to Educative.\n" x += 1 end 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] code end
See the example below of how to write a for
loop in Ruby:
for x in 1..5 print x ,": Welcome to Educative.\n" end
RELATED TAGS
View all Courses