typestar

Loops in Ruby

times, upto, while and each — and why bare for loops are rare.

3.times { |i| puts "pass #{i}" }

1.upto(3) { |n| puts "count #{n}" }

total = 0
while total < 10
  total += 4
end
puts total

[5, 12, 8, 20].each do |n|
  next if n < 10
  puts "big: #{n}"
end

How it works

  1. 3.times and 1.upto(3) loop with the count as a block argument.
  2. while handles open-ended repetition with an explicit condition.
  3. next skips an iteration inside each, like continue elsewhere.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
187
Tokens
74
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 49 seconds.

Type this snippet

Step 3 of 3 in Control flow, step 9 of 29 in Language basics.

← Previous Next →

Loops in other languages