Ruby while Loop

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Ruby while Loop

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:

  1. while conditional [do]  
  2.    code  
  3. end  

Ruby while loop 1

Output:

Ruby while loop 2

Ruby 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:

  1. loop do   
  2.   #code to be executed  
  3.   break if booleanExpression  
  4. end  

Example:

  1. loop do   
  2.   puts "Checking for answer"   
  3.   answer = gets.chomp   
  4.   if answer != '5'   
  5.     break   
  6.   end   
  7. end  

  Output:

Ruby while loop 3