ZetCode

Ruby while Keyword

last modified October 18, 2026

This tutorial explains how to use Ruby's while keyword for creating loops. The while loop executes code repeatedly while a condition is true.

The while keyword creates a loop that runs as long as its condition is truthy. It checks the condition before each iteration. In Ruby, only false and nil are falsey; every other value is truthy. When the condition becomes falsey, the loop terminates.

while loops are fundamental for repetitive tasks in Ruby. They provide precise control over iteration when the number of repetitions isn't known beforehand.

Basic while Loop

This example demonstrates the simplest form of a while loop. The loop continues while the condition remains true.

basic_while.rb
count = 0

while count < 5
  puts "Count is #{count}"
  count += 1
end

puts "Loop finished"

The loop runs while count is less than 5. Each iteration prints the current count and increments it. The loop exits when count reaches 5.

while with User Input

This example uses while to repeatedly prompt for user input until a specific condition is met.

user_input.rb
answer = ""

while answer.downcase != "quit"
  print "Enter a command (or 'quit' to exit): "
  answer = gets.chomp
  puts "You entered: #{answer}"
end

puts "Goodbye!"

The loop continues until the user enters "quit". The condition checks the input in a case-insensitive way. Each iteration processes the user's input.

Infinite while Loop with break

This example shows how to create an infinite loop with while true and use break to exit based on a condition.

infinite_loop.rb
counter = 0

while true
  puts "Counter: #{counter}"
  counter += 1
  
  break if counter >= 10
end

puts "Loop exited"

The loop runs indefinitely until the break condition is met. This pattern is useful when the exit condition is complex or appears mid-loop.

while with next Keyword

This example demonstrates using next to skip certain iterations within a while loop.

next_keyword.rb
num = 0

while num < 10
  num += 1
  next if num.even?
  
  puts "Odd number: #{num}"
end

puts "Done"

The loop skips even numbers using next. Only odd numbers are printed. In a while loop, next jumps back to the condition check. The loop continues until all numbers up to 10 are processed.

while with redo Keyword

The redo keyword restarts the current iteration without checking the loop condition again.

redo_keyword.rb
attempts = 0

while attempts < 2
  attempts += 1
  puts "Attempt #{attempts}"
  redo if attempts == 1
end

The first pass reaches redo and repeats the body, so the second attempt is printed before the loop condition is checked. Because redo skips the condition check, it can create an infinite loop if the repeated code never changes the loop state.

while Modifier Form

Ruby offers a postfix while modifier that executes code while a condition is true. This concise form is useful for single-statement loops.

modifier_form.rb
count = 0

puts count += 1 while count < 5

puts "Final count: #{count}"

The postfix while executes the preceding statement repeatedly. Like the regular form, it checks the condition before the first execution, so it is not a do-while loop. The loop stops when the condition becomes false. This form is compact but less flexible.

begin ... end while (Do-While)

To run the body at least once, put it between begin and end and place while after end. The condition is then checked after each execution.

do_while.rb
count = 0

begin
  puts "Count is #{count}"
  count += 1
end while count < 3

n = 5

begin
  puts "Body ran with n = #{n}"
end while n < 5

The first loop behaves like an ordinary while loop. The second shows the key difference: its body runs once even though the condition is false from the start.

Nested while Loops

This example demonstrates nested while loops to create more complex iteration patterns.

nested_loops.rb
outer = 1

while outer <= 3
  inner = 1
  
  while inner <= outer
    print "#{outer}:#{inner} "
    inner += 1
  end
  
  puts
  outer += 1
end

The outer loop runs three times. The inner loop's iterations increase with each outer iteration. This creates a triangular pattern.

while with Arrays

This example shows how to use while to process array elements without using iterator methods.

array_processing.rb
fruits = ["apple", "banana", "cherry", "date"]
index = 0

while index < fruits.length
  puts "Fruit ##{index + 1}: #{fruits[index].capitalize}"
  index += 1
end

puts "All fruits processed"

The loop processes each array element by index. It continues until all elements are visited. This approach gives manual control over array traversal.

Source

Ruby Keywords Documentation

This tutorial covered Ruby's while loops with practical examples showing basic usage, control flow, and common patterns.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Ruby tutorials.