Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

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

for

A for loop is used to execute a set of code a fixed number of times. The code is executed a fixed number of times because the for loop has a set number of iterations that it will run.

for i in 1..10
  puts i
end
This for loop will print out the numbers 1 through 10.

while

A while loop is used to execute a set of code as long as a certain condition is true. The code will continue to execute as long as the condition is true. Once the condition is no longer true, the code will stop executing.

i = 1

while i <= 10
  puts i
  i += 1
end
This while loop will print out the numbers 1 through 10.

until

An until loop is used to execute a set of code as long as a certain condition is false. The code will continue to execute as long as the condition is false, so it's like the opposite of while loop. Once the condition is true, the code will stop executing.

i = 1

until i > 10
  puts i
  i += 1
end
This until loop will print out the numbers 1 through 10.

do..while

A do..while loop is used to execute a set of code at least once, and then continue to execute the code as long as a certain condition is true. The code will execute at least once because the code is executed before the condition is checked.

i = 1

begin
  puts i
  i += 1
end while i <= 10
This do..while loop will print out the numbers 1 through 10.

.each

A .each loop is used to execute a set of code for each element in a given array or hash.

array = [*1..10]

array.each do |i|
  puts i
end
This .each loop will print out the numbers 1 through 10.