![]() Prev |
![]() Contents |
![]() Next |
Ruby user's guide | Control structures |
This chapter explores more of ruby's control structures.
A while
is a repeated if
.
ruby> i = 0; print i+=1, "\n" while i < 3 1 2 3 nil
We use the case
statement to test for several alternative
values.
ruby> i=8 ruby> case i | when 1, 2..5 | print "1..5\n" | when 6..10 | print "6..10\n" | end 6..10 nil
2..5
is an expression which means the range between 2 and
5, inclusive. The following expression tests whether the
value of i
falls within that range:
(2..5) === i
case
internally uses the relationship operator
===
to check for several conditions at a time. In
keeping with ruby's object oriented nature, ===
is
interpreted suitably for the object that appeared in the when
condition. For example,
ruby> case 'abcdef' | when 'aaa', 'bbb' | print "aaa or bbb\n" | when /def/ | print "includes /def/\n" | end includes /def/ nil
tests string equality in the first when
and regular
expression matching in the second when
.
There are four ways to interrupt the progress of a loop from
inside. First, break
means, as in C, to escape from the
loop entirely. Second, next
skips to the beginning of
the next iteration of the loop (corresponding to C's
continue
). Third, ruby has redo
, which
restarts the current iteration. The following is C code
illustrating the meanings of break
, next,
and
redo
:
while (condition) { label_redo: goto label_next /* next */ goto label_break /* break */ goto label_redo /* redo */ ; ; label_next: } label_break: ;
The fourth way to get out of a loop from the inside is
return
. An evaluation of return
causes
escape not only from a loop but from the method that contains the
loop. If an argument is given, it will be returned from the
method call, otherwise nil
is returned.
The final remaining repetition control structure is
for
.
for i in obj ... end
The for
statement iterates up to end
for
each element of obj, assigning each element into the
variable i
. This is one form of an
iterator; below is the more traditional OOP form, similar to
what you would see in a language like Smalltalk.
obj.each {|i| ... }
The above two forms are equivalent, but depending on your language
background you may find for
to be clearer than
each
. It is one of the reasons that
for
exists. The next page discusses the concept of
iterators in more detail.
![]() Prev |
![]() Contents |
![]() Next |