Sage-Code Laboratory
index<--

Ruby Repetition

This is the second most important statement in a programming language. With decisions and repetitions you can resolving a problems. There are languages that do not have these statements: XML, HTML, and CSS.  We say these languages are not "Turing complete". 

While loop

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.

decision

while loop diagram

Example:

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:

  1. I have used "while" keyword in ways to create loops, 
  2. First is actually a block with "while" augment,
  3. Second is the proper loop controlled by variable "n",
  4. There are two early exit points: abort() and exit(),
  5. The "print" statement is similar to "puts" except it does not add new line.

Homework: open this example live and run-it 2 times: while loop

Loop do

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.

do-while

loop do

Pattern


loop do

 # code to be executed

break if Boolean_Expression

end

Example:


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)

Until loop

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.

do-while

Until Diagram

Example:

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.

For loop

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.

Example:

# 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:

  1. Range notation include both limits,
  2. Range can start from negative number,
  3. Reverse range do not exist actually,
  4. Keyword "do" is optional but is a good practice to use it.

Homework: open example live and run it: for range

Array traversal

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.

Example:

# 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

Interruptions

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:

continue

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

Notes:

  1. operation (x % 2) will return zero if 2 is divisor of x,
  2. this program do not require input and will produce same output every time is run.

Output: To verify the output you must run it: next iteration


Read next: Methods