While. In a program, each statement is sequentially executed. One comes after another. But a looping construct modifies the flow of control—it makes some code repeat.
Constructs. In Ruby the while-loop is one construct. Until is the while-loop's negative friend. While continues when the condition is true, "until" when false.
Warning In the while-loop, we must be careful to avoid an infinite loop. The iteration variable must cause the loop to terminate.
# The iteration variable.
i = 10
# A while-loop.while i < 50
print "i: ", i, "\n"# Increment.
i += 10
endi: 10
i: 20
i: 30
i: 40
Until. An until-loop keeps iterating until the condition evaluates to true. The while-loop continues until the condition is false. This is a syntax change.
Note The until-loop has all the flaws of the while-loop. With logic, we must ensure the loop is not infinite.
# Start at five.
index = 5
# Continued own until zero reached.until index == 0
print "Index: ", index, "\n"
index -= 1
endIndex: 5
Index: 4
Index: 3
Index: 2
Index: 1
For-loop. We use this loop to iterate over a range of numbers. We specify the iteration variable first. And then we indicate a range of numbers. This does not need to be constant.
Here We loop over the values 0 through 5 (inclusively) and the iteration variable "i" is incremented by 1 after each pass.
Detail The range of numbers can have two or three periods in it. The minimum and the maximum can also be variables, not just constants.
# Loop over values 0 through 5.for i in 0..5
puts i
end0
1
2
3
4
5
Break. When this statement is encountered, the loop terminates. Usually loops are clearest when the endpoint is clearly specified in the loop condition. But sometimes this is not possible.
Tip The break statement is often helpful in a while-true loop, which would continue infinitely unless manually stopped.
Here The while-loop continues printing the value until the if-statement evaluates to true. Then the break statement stops the loop.
i = 0
while true
# Break loop if variable is 5 or greater.
if i >= 5
break
end
# Display variable and increment.
puts i
i += 1
end0
1
2
3
4
Next. With this keyword, we can skip to the loop's next iteration. No further statements are executed for the current one. Unlike break, next does not terminate the loop.
Here We test the length of each string in an array. We skip to the next iteration (with next) if a length exceeds 3.
Detail Loops that use "next" can be rewritten with an if-else construct. This makes some loops clearer. But others are clearer with next.
array = ["cat", "dog", "plant", "horse"]
# Loop over values 0 through 3.
for element in array
# Next iteration if length is too big.
if element.length > 3
next
end
# Display element.
puts element
endcat
dog
Redo. Loops support the redo statement. Redo terminates the current iteration, but it does not move to the next one. It restarts from the beginning of the loop, at the same iteration.
Thus The iteration variable (in this program, "A") is not reset. After a redo, it retains the same value.
Here This program illustrates redo. It loops over the values 0 through 3 using a for-loop.
Detail The program generates a random number with rand. If the random number is not equal to 2, we redo the loop iteration.
Warning Redo can lead to infinite loops. Please check that your loop correctly terminates—consider instead the "next" keyword.
# Loop over values 0 through 3.
for a in 0..3
# Get random number.
i = rand 0..4
# Display iteration variable.
puts a# Redo loop if not 2.redo unless i == 2
# Display done after each iteration.
puts "DONE"
end0
DONE
1
1
1
1
DONE
2
2
2
2
2
2
2
2
DONE
3
3
3
DONE
Do-keyword. In looping constructs, the do-keyword is optional. It may also have more symmetry with iterator blocks, which is an advantage. Do is used in other contexts, like iterators.
count = 3
# Use while with optional do-keyword.
while count >= 0do
puts(count)
# Decrement count.
count -= 1
end3
2
1
0
End statement. A loop statement must have an end to it—the end statement is required. This is also true for methods and other kinds of blocks.
Here We find that we get a syntax error, "expecting keyword_end" when end is omitted.
i = 0
# This loop is correct except it has no end-statement.while i < 10
puts(i)
i += 2/test.rb:9: syntax error, unexpected end-of-input, expecting keyword_end
i += 2
^
Iterators. A while-loop can accomplish all looping tasks. But other constructs, called iterators, are also available. They improve the syntax for many loops. They reduce errors.
Detail The yield keyword is used to implement iterators. Often we use yield within a loop, like the while-loop.
A summary. Programs handle not just single units of data, but ranges, collections of data. In loops we handle this data. Nearly every program will have loops.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 8, 2022 (edit link).