Ruby While, Until and For Loop ExamplesLoop over ranges of numbers. See the while-loop, until-loop and other loops.
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.
While.This program uses a simple while-loop. It introduces an iteration variable—this has the identifier "i". We start this variable at 10.
And: We increment the variable by 10, while it is less than 50. We print each iteration value.
Caution: In the while-loop, we must be careful to avoid an infinite loop. The iteration variable must cause the loop to terminate.
|Ruby program that uses while-loop # The iteration variable. i = 10 # A while-loop. while i < 50 print "i: ", i, "\n" # Increment. i += 10 end Output i: 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.
|Ruby program that uses until-loop # Start at five. index = 5 # Continued own until zero reached. until index == 0 print "Index: ", index, "\n" index -= 1 end Output Index: 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.
Range: The range of numbers can have two or three periods in it. The minimum and the maximum can also be variables, not just constants.
|Ruby program that uses for-loop # Loop over values 0 through 5. for i in 0..5 puts i end Output 0 1 2 3 4 5|
Break.When this statement is encountered, the loop terminates. Usually loops are clearest when the end point 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.
|Ruby program that uses break statement 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 end Output 0 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.
Usually: Loops that use "next" can be rewritten with an if-else construct. This makes some loops clearer. But others are clearer with next.
|Ruby program that uses 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 end Output cat 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.
Rand: The program generates a random number with rand. If the random number is not equal to 2, we redo the loop iteration.Unless
Caution: Redo can lead to infinite loops. Please check that your loop correctly terminates—consider instead the "next" keyword.
|Ruby program that uses redo # 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" end Output 0 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.
|Ruby program that uses do-keyword count = 3 # Use while with optional do-keyword. while count >= 0 do puts(count) # Decrement count. count -= 1 end Output 3 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.
|Ruby program that causes syntax error i = 0 # This loop is correct except it has no end-statement. while i < 10 puts(i) i += 2 Output /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.
Yield: 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.
Considerations.Each of these looping constructs has its pitfalls and benefits. Usually we prefer iterators over loops in Ruby programs. But each has its place.
Dot Net Perls
|© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, email@example.com.|