How to create loops in Ruby

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.





Different types of loops (Ruby)


While Statement

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.

Syntax

while conditional [do]
code
end

Code

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


While modifier

begin and end can also be used to create a while loop.

Syntax

begin
code
end while [condition]

Code

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


Until statement

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.

Syntax

until conditional [do]
code
end

Code

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


Until modifier

Like the while modifier, begin and end can also be used ​to create an until loop.

Syntax

begin
code
end until [condition]

Code

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


For statement

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.

Syntax

for variable [, variable ...] in expression [do]
code
end

Code

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

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved