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
3.timesand1.upto(3)loop with the count as a block argument.whilehandles open-ended repetition with an explicit condition.nextskips an iteration insideeach, like continue elsewhere.
Keywords and builtins used here
doendifnextputswhile
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.
Step 3 of 3 in Control flow, step 9 of 29 in Language basics.