A repetitive statement is often called loop. Diverse kind of loops are controlled by different methods. A loop can repeat forever if you are not careful. This may be an error made by beginners. If you make this error, do not be intimidated. Just press Ctrl+C to kill your process.
while loop diagram
While loop is executed until a control condition become false.
# enter number between 1 and 5
begin
print "how many? (1..5):"
$count = gets.to_i
end while $count > 5
# early termination
abort("done") if $count == 0
n = 0 #control variable
# wile loop with control variable
while n < $count do
print n += 1, ","
end
exit(0) # early termination
puts "ok" # dead code
Note: A lot is happening in this short example:
Homework: open this example live and run-it 2 times: while loop
This is known in other languages like: do-while loop. It execute at least one time and it repeats infinite number of times if there is no break condition. You must use expression "break if" before the end of block so that the repetition can stop.
loop do
loop do
# code to be executed
break if Boolean_Expression
end
def nearest_larger(arr, idx)
diff = 1
loop do
left = idx - diff
right = idx + diff
if (left >= 0) && (arr[left] > arr[idx])
return left
elsif (right < arr.length) && (arr[right] > arr[idx])
return right
elsif (left < 0) && (right >= arr.length)
return nil
end
diff += 1
end
end
nearest_larger([2,4,3,8], 1)
The until statement is similar to the while statement in functionality. Unlike the while statement, the code block for the until loop will execute as long as the control condition evaluates to false. When this condition become true the loop will stop.
Until Diagram
This example should look familiar by now. It is similar with previous one.
# execute at least once
begin
print "iterations (1..8):"
$count = gets.to_i
end until $count <= 8
# early termination
abort("Abort!") if $count <= 0
n = $count #control variable
# until loop with control variable
until n == 0 do
print n
print "," if n > 1
n -= 1;
end
puts "\nDone!" # finish
Note: In my opinion "until" is redundant, but in Ruby you can do same thing in many ways. In previous example you can observe the loop display numbers in reverse order and the last comma is not display.
Homework: run this example: until loop
Single line:
You can create a loop in a single statement. Your program will look very strange for someone who do not understand Ruby. The next code fragment will read input values until the value is right:
print "enter a value between (1..5)";
a = 0;
a = gets.to_i until (1..5).include?(a)
Note: Previous example accept input and validate against range (1..5). If the value you enter is in range the statement terminates otherwise is waiting for the next input until you get it right.
This kind of loop is sometimes called iteration. It will repeat a statement or a group of statements of specific number of times. It is controlled by a range of values. Same loop can also iterate over items of a collection.
# read one number in range
print "iterations (0..10):"
x = gets.to_i until (0..10) === x
# print a list of numbers
print "\nAscending:"
for n in 0..x do
print n
print "," if n < x
end
print "\nIn reverse:"
# print a list of numbers in revers
for n in -x..0 do
print -n
print "," if n < 0
end
puts "\nDone!" # finish
Note:
Homework: open example live and run it: for range
You can use "for" loop to visit all elements from an array. Actually this kind of loop is very similar with previous. The only difference is the loop is controlled by the collection. When all elements of collection are visited the loop will stop.
# read one number in range
print "iterations (0..10):"
x = gets.to_i until (0..10) === x
array = (0..x).to_a # create an array
print "array = ", array
# for loop visitor pattern
print "\nFor loop: "
for e in array do
print e," "
end
Note: In this example:
Homework: Open this example live and run it: for-each
If you are familiar with other computer languages you should know any loop statement can be interrupted earlier. This is done with additional keywords that can be used with conditionals to control nested loops or complex situations:
Loop Intreruptions
Example
# print only odd numbers
puts "odd:"
for x in 1..10 do
next if x % 2 == 0
print x," " # 1 3 5 7 9
end
# print only even numbers
puts
puts "even:"
for x in 1..10 do
next if x % 2 != 0
print x," " # 2 4 6 8 10
end
Output: To verify the output you must run it: next iteration
Read next: Methods