Loops & Iterators

💎 Ruby Lesson 5 Beginner

Ruby provides standard loops, until loops, and block-based numerical iterators like times.

1 Iterators vs. Standard Loops

While Ruby supports standard `while` loops, idiomatic Ruby code prefers **block iterators** like `times`, `upto`, and `step`, which take closures to iterate safely and cleanly:

  • `until`: Loop executes as long as a condition is **false** (opposite of while).
  • `times`: Repeats a block a specific number of times: `5.times { |i| puts i }`.
2 Loops Code

Let's run a program illustrating loops, until statements, and times iterators:

Ruby — Loops ▶ Run Code
# 1. Until loop (runs until condition is true)
count = 1
print "Until loop: "
until count > 5
  print "#{count} "
  count += 1
end
puts

# 2. Block-based Times iterator
print "Times iterator: "
3.times do |index|
  print "Count:#{index} "
end
puts

# 3. Upto iterator
print "Upto loop: "
1.upto(4) { |num| print "#{num} " }
puts
3 Code Challenge
Challenge: Write an iterator sequence using `downto` that counts down from 5 to 1 and outputs a final message.