The Wayback Machine - https://web.archive.org/web/20240717024532/https://www.geeksforgeeks.org/ruby-loops-for-while-do-while-until/
Open In App

Ruby | Loops (for, while, do..while, until)

Last Updated : 05 Jul, 2021
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Looping in programming languages is a feature which clears the way for the execution of a set of instructions or functions repeatedly when some of the condition evaluates to true or false. Ruby provides the different types of loop to handle the condition based situation in the program to make the programmers task simpler. The loops in Ruby are :
 

 

 

 

while Loop

The condition which is to be tested, given at the beginning of the loop and all statements are executed until the given boolean condition satisfies. When the condition becomes false, the control will be out from the while loop. It is also known as Entry Controlled Loop because the condition to be tested is present at the beginning of the loop body. So basically, while loop is used when the number of iterations is not fixed in a program. 
Syntax:
 

while conditional [do]

 # code to be executed

end

Note: A while loop’s conditional is separated from code by the reserved word do, a newline, backslash(\), or a semicolon(;).
Flowchart:
 

Example:
 

Ruby




# Ruby program to illustrate 'while' loop
 
# variable x
x = 4
 
# using while loop
# here conditional is x i.e. 4
while x >= 1
 
# statements to be executed
  puts "GeeksforGeeks"
  x = x - 1
   
# while loop ends here
end


Output:
 

GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks

 

for Loop

“for” loop has similar functionality as while loop but with different syntax. for loop is preferred when the number of times loop statements are to be executed is known beforehand. It iterates over a specific range of numbers. It is also known as Entry Controlled Loop because the condition to be tested is present at the beginning of the loop body.
Syntax:
 

for variable_name[, variable...] in expression [do]

   # code to be executed

end

for: A special Ruby keyword which indicates the beginning of the loop.
variable_name: This is a variable name that serves as the reference to the current iteration of the loop. 
in: This is a special Ruby keyword that is primarily used in for loop.
expression: It executes code once for each element in expression. Here expression can be range or array variable.
do: This indicates the beginning of the block of code to be repeatedly executed. do is optional.
end: This keyword represents the ending of ‘for‘ loop block which started from ‘do‘ keyword.
Example 1:
 

Ruby




# Ruby program to illustrate 'for'
# loop using range as expression
 
i = "Sudo Placements"
 
# using for loop with the range
for a in 1..5 do
     
 puts i
  
end


Output: 
 

Sudo Placements
Sudo Placements
Sudo Placements
Sudo Placements
Sudo Placements

Output: 
 

1
2
3
4
5

Explanation: Here, we have defined the range 1..5. Range Operators create a range of successive values consisting of a start, end, and range of values in between. The (..) creates a range including the last term. The statement for a in 1..5 will allow a to take values in the range from 1 to 5 (including 5).
Example 2:
 

Ruby




# Ruby program to illustrate 'for'
# loop using array  as expression
 
# array
arr = ["GFG", "G4G", "Geeks", "Sudo"]
 
# using for loop
for i in arr do
     
 puts i
  
end


Output: 
 

GFG
G4G
Geeks
Sudo

 

do..while Loop

do while loop is similar to while loop with the only difference that it checks the condition after executing the statements, i.e it will execute the loop body one time for sure. It is a Exit-Controlled loop because it tests the condition which presents at the end of the loop body. 
Syntax:
 

loop do

 # code to be executed

break if Boolean_Expression

end

Here, Boolean_Expression will result in either a true or false output which is created using comparing operators (>, =, <=, !=, ==). You can also use multiple boolean expressions within the parentheses (Boolean_Expressions) which will be connected through logical operators (&&, ||, !).
Example:
 

Ruby




# Ruby program to illustrate 'do..while'loop
 
# starting of do..while loop
loop do
     
 puts "GeeksforGeeks"
  
 val = '7'
  
 # using boolean expressions
 if val == '7'
  break
 end
  
# ending of ruby do..while loop
end


Output: 
 

GeeksforGeeks

 

until Loop

Ruby until loop will executes the statements or code till the given condition evaluates to true. Basically it’s just opposite to the while loop which executes until the given condition evaluates to false. An until statement’s conditional is separated from code by the reserved word do, a newline, or a semicolon.
Syntax: 
 

until conditional [do]

 # code to be executed

end

Example:
 

Ruby




# Ruby program to illustrate 'until' loop
 
var = 7
 
# using until loop
# here do is optional
until var == 11 do
 
  # code to be executed
  puts var * 10
  var = var + 1
   
# here loop ends
end


Output: 
 

70
80
90
100

 



Previous Article
Next Article

Similar Reads

Difference between Ruby and Ruby on Rails
1. Ruby : Ruby is an object-oriented scripting language launched in 1995 and is known as a general-purpose programming language. It was programmed in C programming language. Ruby is a secured programming language and its syntax is similar to Perl and Python. It was developed on the principle of user interface design and it is mainly used to develop
3 min read
Private Classes in Ruby
The concept of private, protected and public methods in Ruby is a bit different than it other languages like Java. In Ruby, it is all about which class the person is calling, as classes are objects in ruby. Private Class When a constant is declared private in Ruby, it means this constant can never be called with an explicit receiver, a private cons
3 min read
Ruby | Matrix cofactor() function
The cofactor() is an inbuilt method in Ruby returns the cofactor of the given index. Syntax: mat1.cofactor(i, j) Parameters: The function needs two index i and j, whose cofactor is to be returned. Return Value: It returns the cofactor of the given index. Example 1: # Ruby program for cofactor() method in Matrix # Include matrix require &quot;matrix
1 min read
Ruby Integer odd? function with example
The odd? function in Ruby returns a boolean value. It returns true if the number is odd, else it returns false. Syntax: number.odd? Parameter: The function takes the integer which is to be checked for odd or not. Return Value: The function returns a boolean value which determines if the value is odd or not. Example #1: # Ruby program of integer odd
1 min read
Ruby Integer div() function with example
The div() function in Ruby returns the integer division of two numbers. Syntax: (number1).div(number2) Parameter: The function needs two numbers number1 and number2, where number1 is the dividend and number2 is the divisor. Return Value: The function returns the integer division of two numbers. Example #1: # Ruby program of Integer div() function #
1 min read
Ruby | Symbol to_s function
Symbol#to_s() : to_s() is a Symbol class method which returns string representation of the symbol object. Syntax: Symbol.to_s() Parameter: Symbol values Return: string representation of the symbol object. Example #1 : # Ruby code for Symbol.to_s() method # declaring Symbol a = :aBcDeF # declaring Symbol b = :&quot;\u{e4 f6 fc}&quot; # declaring Sym
1 min read
Ruby | Set replace() function
The replace() is an inbuilt method in Ruby which replaces the contents of the set with the contents of the given enumerable object and returns self. Syntax: s1.replace(enum) Parameters: The function accepts an enumerable object which to be replaced in the set. Return Value: It returns the self object which contains the contents of the set after rep
1 min read
Ruby | Set reset() function
The reset() is an inbuilt method in Ruby resets the internal state after modification to existing elements and returns self. The elements will be reindexed and deduplicated. Syntax: s1.reset() Parameters: The function does not accepts any parameter. Return Value: It returns self . Example 1: # Ruby program to illustrate # the reset() method # requi
1 min read
Ruby | Array Concatenation using (+) function
Array#+() is a Array class method which performs set concatenate operation arrays by combining two arrays to a third array. Syntax: Array.+() Parameter: Arrays for performing the concatenation operation. Return: New arrays by combining two arrays. Example #1 : # Ruby code for +() method # showing concatenate operation # declaring array a = [18, 22,
2 min read
Ruby | at() function
The at() function in Ruby is used to return the element of the specified index. Index 0 is for the first element of the array, 1 for the second element of the array and so on. The negative index counts from the end of the input array. Syntax: Array.at(Index) Here Array is the input array of elements at which at() function is called. Parameters: Ind
2 min read
Article Tags :
three90RightbarBannerImg