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.
while conditional [do] code end
x = gets.chomp.to_i while x >= 0 puts x x -=1 end
5 #This is user input 5 #Output start from here 4 3 2 1 0
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.
loop do #code to be executed break if booleanExpression end
loop do puts "Checking for answer" answer = gets.chomp if answer != '5' break end end
Hope you guys found this page helpful 🙂