Prev - DUP - Next - TOC

Control structures


This chapter shows ruby's control structures. We have seen `if', `while' and `break' already. Others are shown here.

We know of an `if' modifier, there is also a `while' modifier.

 ruby> i = 0; print i+=1, "\n" while i < 3
 1
 2
 3
 nil

We use the `case' statement to check for many options. It will be written as follows:

 ruby> case i
 ruby| when 1, 2..5
 ruby|   print "1..5\n"
 ruby| when 6..10
 ruby|   print "6..10\n"
 ruby| end
 6..10
 nil

where `2..5' is an expression which means the range between 2 and 5. In above example, the result of the following expression is used to decide whether or not `i' is in the range as follows.

 (2..5) === i

As this instance, `case' uses the relationship operator `===' to check for each conditions at a time. By ruby's object oriented features, the relationship operator `===' is interpreted suitably for the object appeared in the `when' condition. For example,

 ruby> case 'abcdef'
 ruby| when 'aaa', 'bbb'
 ruby|   print "aaa or bbb\n"
 ruby| when /def/
 ruby|   print "includes /def/\n"
 ruby| end
 includes /def/
 nil

tests equality as strings or string matching to regular expressions.

There are three controls to escape from a loop. `break' means, as in C, to escape from the loop. `next' corresponds to `continue' in C, and is used for skipping the rest of loop once and going to the next iteration. Additionally, ruby has `redo', which executes the current iteration again. The following C code is witten in order to help C users undestand.

  while (condition) {
   label_redo:
     goto label_next        /* next */
     goto label_break       /* break */
     goto label_redo        /* redo */
     ;
     ;
   label_next:
  }
  label_break:
  ;

The last way is `return'. A evaluation of `return' causes escaping. If an argument is given it will be the return value, otherwise ruby assumes that an argument `nil' is given.

One more repetition control structure is left, that is `for'. It is used as follows.

 for i in obj
  ...
 end

The `for' statement iterates up to `end' for each elements of 'obj', with substituting each of them to the variable `i'. This is the alternative form of the iterator, which will be mentioned later. See the following for example of iterator.

 obj.each {|i|
  ...
 }

Both of above two forms are equivalent, but you may understand `for' more than `each'. It is one of the reasons that `for' exists.


Prev - DUP - Next - TOC