Thuta Learning
IntermediateProgrammingbeginner

Loops (While, Until)

Relax. We'll talk through this in plain words — no textbook voice.

A loop is a way to run a piece of code over and over again. Ruby has while and until, but for collections, people tend to reach for each more often.

ruby
count = 1

while count <= 3
  puts "While count: #{count}"
  count += 1
end

counter = 1
until counter > 3
  puts "Until counter: #{counter}"
  counter += 1
end

while keeps running as long as the condition is true. until keeps running as long as the condition is false. If you forget to update the counter on every pass, you can end up with an infinite loop.

You should see
While count: 1 While count: 2 While count: 3 Until counter: 1 Until counter: 2 Until counter: 3

Info

count += 1 is the same as count = count + 1.

Easy traps

  • If you forget to update the counter, the loop will never end. If your terminal gets stuck, you can stop it with Ctrl + C.
Loops (While, Until) | Thuta Learning