Ruby For Loops
A for loop is a loop that runs once for each value in a range. The loop name takes each value in turn.
For over a range
The name i takes each value in the range. Each turn prints the value i holds.
for i in 1..5
puts i
endFor over a range without its end
Three dots leave the end value out. The loop stops before the value 4.
for i in 1...4
puts i
endA step pattern with for
The loop still takes each value in turn. Each turn prints the value times two.
for i in 1..4
puts i * 2
endExample
for n in 1..3
puts "Turn #{n}"
end
for n in 1...3
puts n * 10
endKey points
- A for loop writes for, a name, the word in, and a range.
- The body runs once for each value in the range.
- The loop name holds the current value on each turn.
- A range with three dots leaves the last value out of the loop.
- A for loop needs no line that updates the count.
In this example, the first loop runs for the values 1, 2, and 3. Each turn puts the value of n into the printed text. The second loop runs for the values 1 and 2, since three dots leave the end value out. Each turn prints the value times ten. A later lesson shows a for loop running over an array, a single value that holds many values in order.
Note
The range supplies the next value on each turn, so the loop ends at the end of the range.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Ruby Compiler
Exercise
What decides how many turns a for loop runs?