While loop and do while loop in Ruby

The Ruby while loop is used to iterate a program several times. If the number of iterations is not fixed for a program, while loop is used.

Ruby while loop executes a condition while a condition is true. Once the condition becomes false, while loop stops its execution.

Syntax:

while conditional [do]  
   code  
end  

Example:

x = gets.chomp.to_i   
while x >= 0    
  puts x   
  x -=1   
end   

Output:

5 #This is user input
5 #Output start from here
4
3
2
1
0

Do…while loop:

The Ruby do while loop iterates a part of program several times. It is quite similar to a while loop with the only difference that loop will execute at least once. It is due to the fact that in do while loop, condition is written at the end of the code.

Syntax:

loop do   
  #code to be executed  
  break if booleanExpression  
end   

Example:

loop do   
  puts "Checking for answer"   
  answer = gets.chomp   
  if answer != '5'   
    break   
  end   
end  

Output:

Hope you guys found this page helpful 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.