OneBite.Dev - Coding blog in a bite size

do a while loop in Ruby

Code snippet on how to do a while loop in Ruby

i = 0

while i < 5
  puts i
  i += 1
end

This code is a while loop which will print the numbers 0-4. The variable “i” is initialized to 0 and then the while loop begin to execute. Inside the while loop there is a command to print the value of variable “i”, followed by a command to add one to the variable. The while loop will repeat this process until the variable “i” is no longer smaller than 5. In this case, it will only print 0-4 since the number 5 is not reached. Finally, when 5 is reached, the loop will exit and no more numbers will be printed on the screen.

ruby