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]codeend
Code
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
While modifier
begin and end can also be used to create a while loop.
Syntax
begincodeend while [condition]
Code
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
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]codeend
Code
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
Until modifier
Like the while modifier, begin and end can also be used to create an until loop.
Syntax
begincodeend until [condition]
Code
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
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]codeend
Code
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