The best examples of Ruby looping constructs: 3 practical examples for real projects

If you’re learning Ruby in 2024 and want clear, real examples of Ruby looping constructs: 3 practical examples stand out as the workhorses you’ll use constantly: `each`, `times`, and `while`. These three loops show up in everything from Rails apps to quick automation scripts, and understanding them with real examples will make your code cleaner, faster to write, and easier to debug. In this guide, we’ll walk through examples of Ruby looping constructs: 3 practical examples that mirror how developers actually write Ruby day to day. We’ll iterate over arrays of users, handle retry logic for flaky APIs, and generate reports from simple data structures. Along the way, you’ll see how these loops compare, when to use each one, and how modern Ruby style (as of 3.2 and beyond) encourages certain patterns. By the end, you won’t just “know” loops in theory—you’ll have a set of patterns you can drop straight into production code or your next coding interview.
Written by
Jamie
Published
Updated

3 practical examples of Ruby looping constructs you’ll actually use

Let’s skip theory and go straight into examples of Ruby looping constructs: 3 practical examples that mirror real-world work:

  • Iterating over collections with each
  • Running code a fixed number of times with times
  • Looping until a condition changes with while

These are not the only looping tools in Ruby, but they’re the ones you’ll see in nearly every codebase, from legacy Rails apps to modern microservices.


Example 1: Using each to iterate over collections

When developers talk about examples of Ruby looping constructs, each is usually the first one mentioned. It’s the idiomatic way to loop over arrays, hashes, and other enumerable objects.

Processing an array of users

users = [
  { name: "Alice", active: true },
  { name: "Bob",   active: false },
  { name: "Cara",  active: true }
]

active_users = []

users.each do |user|
  next unless user[:active]
  active_users << user[:name]
end

puts "Active users: #{active_users.join(', ')}"
## => Active users: Alice, Cara

Why this is one of the best examples of Ruby looping constructs:

  • Uses each to walk through an array of hashes.
  • Shows next to skip items that don’t meet a condition.
  • Produces a clean list of active user names, exactly the kind of pattern you see in business logic.

Iterating over a hash of configuration values

config = {
  max_retries: 3,
  timeout_ms:  1_000,
  region:      "us-east-1"
}

config.each do |key, value|
  puts "Config #{key}: #{value}"
end

This example of Ruby looping constructs shows how each works with key–value pairs. In real projects, you’ll see this used to:

  • Log configuration at startup
  • Migrate settings from one system to another
  • Validate configuration against a schema

Streaming data in chunks (2024-style processing)

With more apps processing streams of data (logs, analytics, event queues), Ruby’s each loop pairs well with lazy enumerators:

File.open("events.log") do |file|
  file.each_line.lazy
      .select { |line| line.include?("ERROR") }
      .first(100)
      .each do |error_line|
        puts error_line
      end
end

Here you get:

  • A modern 2024-style pattern: lazy processing instead of loading everything into memory.
  • Another one of the best examples of Ruby looping constructs for real systems, especially logging and monitoring tools.

If you want to go deeper into how Ruby’s Enumerable works under the hood, the Ruby docs at ruby-lang.org are still the gold standard.


Example 2: Using times for predictable, fixed loops

The next set of examples of Ruby looping constructs: 3 practical examples wouldn’t be complete without times. Whenever you know exactly how many iterations you need, times is your friend.

Simple repetition: retrying an API call

In 2024, everything talks to an API. Those APIs fail. A classic example of Ruby looping constructs is using times for retries:

MAX_RETRIES = 3

MAX_RETRIES.times do |attempt|
  begin
    response = HTTP.get("https://api.example.com/data")
    puts "Success on attempt ##{attempt + 1}"
    break
  rescue HTTP::Error => e
    puts "Attempt ##{attempt + 1} failed: #{e.message}"
    sleep(2) if attempt < MAX_RETRIES - 1
  end
end

This snippet shows:

  • Fixed number of attempts (MAX_RETRIES.times).
  • Access to the current index (attempt).
  • A very real example of Ruby looping constructs used in production-grade code.

Generating test data

Developers still write a lot of test and seed data by hand. times keeps this readable:

users = []

10.times do |i|
  users << {
    id:    i + 1,
    email: "user#{i + 1}@example.com"
  }
end

puts users.first(3)

This is one of the best examples of Ruby looping constructs for:

  • Seeding development databases
  • Creating fixtures for RSpec or Minitest
  • Quick prototypes where you need data, not perfection

Scheduling recurring jobs (conceptual example)

In background job systems (Sidekiq, Resque, etc.), you’ll often schedule repeated work. Even if the actual scheduling is handled by the library, you might still use times to enqueue multiple jobs:

5.times do |i|
  ReportJob.perform_async(Date.today - i)
end

This example of Ruby looping constructs mirrors a common scheduling pattern: enqueue the last 5 days of reports.

For more structured thinking about loops and control flow, general CS resources like MIT’s open courseware on algorithms (mit.edu) are still very relevant, even if they’re language-agnostic.


Example 3: Using while for condition-based looping

Now for the third in our set of examples of Ruby looping constructs: 3 practical examples—while. This loop keeps running as long as a condition stays true. It’s perfect when you don’t know in advance how many times you’ll need to iterate.

Polling until a job finishes

Asynchronous work is everywhere now: background jobs, queues, serverless tasks. A classic example of Ruby looping constructs is polling until something is done:

job_id = JobQueue.enqueue(:generate_report)

status = nil

while status != :finished
  status = JobQueue.status(job_id)
  puts "Current status: #{status}"

  break if status == :failed

  sleep(1)
end

puts "Job completed with status: #{status}"

This loop:

  • Uses while to keep checking status.
  • Breaks early if the job fails.
  • Mirrors real infrastructure code you’ll see in 2024 cloud-based systems.

Reading from a stream until there’s nothing left

Another realistic example of Ruby looping constructs: reading until EOF (end of file or stream):

socket = TCPSocket.new("example.com", 3000)

while (line = socket.gets)
  puts "Received: #{line}"
end

socket.close

This pattern shows up in:

  • Network daemons
  • Chat servers
  • Simple custom protocols and tooling

Simple countdown with validation

Sometimes you just want a clear, readable condition:

countdown = 5

while countdown > 0
  puts "Launching in #{countdown}..."
  countdown -= 1
  sleep(1)
end

puts "Liftoff!"

This is a straightforward example of Ruby looping constructs, but it’s also a nice reminder: use while when the condition is the star of the show.

If you’re interested in how looping and control flow affect performance and readability more broadly, many university style guides—like those from Harvard’s CS50—encourage exactly this kind of clear, condition-driven code.


Beyond the big three: other real examples of Ruby looping constructs

We’ve focused on examples of Ruby looping constructs: 3 practical examples (each, times, while) because they’re the most common. But it helps to see them in context with a few close relatives.

until as the inverse of while

until runs while the condition is false. It’s often more readable when you’re waiting for something to become true.

ready = false

until ready
  ready = system_check_passed?
  puts "System not ready yet" unless ready
  sleep(2)
end

puts "System is ready!"

Same effect as while !system_check_passed?, but easier on the eyes.

for loops (rare in modern Ruby)

You can write:

for i in 1..5
  puts i
end

But most Rubyists prefer 5.times or (1..5).each. If you’re looking for the best examples of Ruby looping constructs in modern code, for is usually not on that list.

loop do with manual breaks

loop do gives you an infinite loop that you control with break:

loop do
  print "Enter command (q to quit): "
  input = gets&.chomp
  break if input == "q"

  puts "You entered: #{input}"
end

This is useful for REPL-style tools, CLIs, and interactive scripts.


How to choose between these examples of Ruby looping constructs

When you’re deciding which construct to use, think in terms of intent:

  • You have a collection? Reach for each.
  • You know the exact number of iterations? Use times.
  • You’re waiting on a condition that may change over time? while (or until) is your tool.

Some quick real examples:

  • Analytics script: Use each to iterate through events and times to generate sample events.
  • Web scraper: Use while to keep following next_page links until there are none.
  • Background processing: Use each for batches of records, times for retries, and while for polling job status.

These patterns line up nicely with general programming guidance from academic and industry sources. For instance, the structured approach to loops and invariants you see in algorithm courses (like those linked from nist.gov when they talk about secure coding practices) aligns well with Ruby’s expressive control flow.


FAQ: common questions about examples of Ruby looping constructs

Q1: What are the most common examples of Ruby looping constructs used in modern code?
The most common examples of Ruby looping constructs you’ll see in 2024 Ruby and Rails code are each, times, and while. each dominates when working with arrays and hashes, times handles fixed iteration counts (like retries or test data), and while is used for condition-based loops such as polling, countdowns, or reading from sockets.

Q2: Can you give an example of converting a while loop to an each loop?
Yes. Suppose you have:

i = 0
while i < items.length
  process(items[i])
  i += 1
end

A more Ruby-style example of looping constructs would be:

items.each do |item|
  process(item)
end

Same behavior, less boilerplate, and fewer chances to introduce off-by-one bugs.

Q3: Are for loops bad in Ruby if they’re also examples of looping constructs?
They’re not “bad,” but they’re rarely the best examples of Ruby looping constructs in idiomatic code. for loops don’t create a new scope for block variables, which can lead to subtle bugs. Most Ruby style guides recommend each, times, and other enumerable methods instead.

Q4: How do these examples of Ruby looping constructs affect performance?
In most web or scripting workloads, the difference between each, times, and while is minor compared to I/O, database calls, or network latency. Micro-optimizing loops is rarely worth it. Focus instead on choosing the construct that makes your intent obvious. When performance does matter, profiling tools (like benchmark from Ruby’s standard library) give you concrete data instead of guesswork.

Q5: Which example of a Ruby looping construct is best for beginners to master first?
Start with each. It’s the backbone of Ruby’s collection processing and shows up everywhere—from iterating ActiveRecord relations in Rails to walking through arrays of data in scripts. Once you’re comfortable with each, times and while will feel natural, and the full set of examples of Ruby looping constructs: 3 practical examples will fit together in your mental model.

Explore More Ruby Code Snippets

Discover more examples and insights in this category.

View All Ruby Code Snippets