HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to RubyVariablesData TypesOperatorsStringsArraysHash (Dictionary)Conditions (if / else)LoopsMethods (def)Classes
REFERENCE
📖 Overview
🖥️ Output & Input
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array
🗂️ Hash (Dictionary)
🔁 Condition & Loop
🧩 Method & Class
Ruby›Loops

Loops

Repeating with times, range (1..n).each, arr.each, and while.

Simple enough for a 5-year-old to understand

times and range

In Ruby, times and each are preferred over for — they are more readable.

Example code
1
3.times { |i| puts i }
Writes 0, 1, 2.
LoopWrites 0, 1, 2.
2
(1..3).each { |n| puts n * 10 }
Prints 10, 20, 30.
LoopPrints 10, 20, 30.
Loop
💡 Hint: The range (1..5) is from 1 to 5 (inclusive); (1...5) excludes 5.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Iterate through the range (1..5) using each and print each number on a new line.

🎯 Expected output: 1 2 3 4 5

Loading editor…

About this topic

It is possible to write a counted loop in Ruby, but it is not customary. Ruby's way is iterator methods: you traverse with each, and repeat a specific number of times with times. Since index management is not left to you, you cannot make an off-by-one error.

At the core of this approach is the concept of a block. You can think of a block as an anonymous piece of code passed to a method; the method calls it as many times as it needs. All of Ruby's collection methods work with this mechanism.

Ruby still offers while and until. These are necessary for situations where the number of repetitions is not known in advance — such as reading from a file or waiting until a condition is met. In these cases, forgetting to increment the counter produces an infinite loop.

What you will learn

  • Traversing with each and times
  • Two forms of block syntax
  • Using while and until
  • The difference between break and next
  • Iterating over a range

When to use?

If you are traversing elements of a collection, use each, or map if transformation is needed; a counted loop is rarely the right tool in Ruby.

If the number of repetitions is not known in advance, while is used; reading files and waiting for user input are typical examples.

Common mistakes

Wrong

i = 0
while i < 3
  puts i
end

Since the counter is not incremented, the condition never becomes false and the loop goes on forever; the program doesn't stop. Forgetting to write the increment inside the body when using while is the most common mistake. This error does not occur because the times method manages the counter itself.

Correct

3.times do |i|
  puts i
end

Wrong

numbers = [1, 2, 3, 4]
numbers.each do |n|
  next if n.even?
  break if n > 3
  puts n
end

This code works, but order matters: the odd number greater than three is never reached because the even ones are already skipped. More importantly, break and next are frequently confused — next skips this step, break terminates the loop entirely. Using both in the same block obscures the intent.

Correct

numbers = [1, 2, 3, 4]
numbers.each do |n|
  next if n.even?
  puts n
end

Wrong

(1..5).each do |i|
  total = 0
  total += i
end
puts total

Since total is defined INSIDE the block, it ceases to exist when the block ends; outside, you get an "undefined local variable or total" error. Furthermore, it resets at every step. Variables defined outside the block are visible from inside the block, but the reverse is not true.

Correct

total = 0
(1..5).each do |i|
  total += i
end
puts total

Frequently asked questions

What is the difference between curly braces and do-end?

Functionally the same, only their precedence differs. The community convention is: curly braces for single-line blocks, do-end for multi-line blocks. This distinction makes the code easier to visually scan.

Why is the for loop not used?

It works, but it is not customary in Ruby because it does not create a new scope: the loop variable lives on after the loop. each creates a new scope and does not leak the variable outside, which is why it is preferred.

Can I break out of a nested loop with a single break?

break only breaks the innermost loop. To break out of two loops at once in Ruby, moving the logic into a method and using return is the most readable way. The less commonly used throw and catch pair also exists for this job.

Summary

Ruby's customary way is iterator methods, not counted loops.

times and each take care of counter management, eliminating the risk of out-of-bounds errors.

next skips this step, break terminates the loop entirely.

A variable defined inside a block ceases to exist once the block ends.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code