Loops
| while and until | |
| for-in | |
| each is the idiom | |
| times upto downto |
while and until
A while loop repeats its body while the condition stays true. An until loop does the opposite: it repeats while the condition stays false, and stops once the condition becomes true. Both check the condition before each pass, so the body must move the counter toward the finish.
i = 1
while i <= 3 do
puts i
i += 1
end
n = 3
until n == 0 do
puts n
n -= 1
end
1
2
3
The first loop prints 1, 2, 3. The second loop counts down and prints 3, 2, 1. Forgetting to change the counter inside the body gives an endless loop, so check that first when a loop never stops.
for-in
A for loop walks each element of an array or a range into a loop variable. The variable stays visible after the loop ends, which surprises many newcomers, so prefer each for everyday iteration.
for n in 1..3 do
puts n
end
This prints 1, 2, 3, exactly like the while version, with less bookkeeping and no manual counter.
each is the idiom
The method each is the Ruby way to iterate. Almost every collection understands it: arrays, hashes, and ranges alike. Attach a block with do and end, and the block variable lives only inside the block.
names = ["Ada", "Bob", "Lin"]
names.each do |name|
puts name
end
(1..3).each do |n|
puts n
end
Ada
Bob
Lin
The range version prints 1, 2, 3. When you read Ruby code in the wild, most loops look like this: a collection, a call to each, and a small block.
times upto downto
Integers are loop factories too. The method times repeats a block a fixed number of times with the index starting at 0. The methods upto and downto count from one bound to another in either direction.
3.times do |i|
puts i
end
1.upto(3) do |i|
puts i
end
3.downto(1) do |i|
puts i
end
0
1
2
The upto loop prints 1, 2, 3, and the downto loop prints 3, 2, 1. Reach for these when the count itself drives the work.
Next: Arrays
Article author: Arthur Isaev