Control Structures

Unlike in C, control structures in Ruby are expressions that return some value.

Ruby carries over some control structures from C and Perl, but also features a loop abstraction feature called iterators. Iterators are user-definable looping control structures.

Conditional Branching

if

Examples:

if age >= 12 then
  print "adult fee\n"
else
  print "child fee\n"
end
gender = if foo.gender == "male" then "male" else "female" end

Syntax:

if expr [then]
  expr ...
[elsif expr [then]
  expr ... ]
...
[else
  expr ... ]

end

If a conditional expression is evaluated as true, evaluates the expression beginning with then. If the if expression is false, evaluates the elsif condition. Multiple elsif clauses can be specified; when all if or elsif conditional expressions are false, the else clause expression, if any, is evaluated.

if returns the value of the last evaluated expression in the conditional expression clause (or else clause). If there is no else clause and no conditional expressions in effect, returns nil.

The values false and nil are false; everything else, including zero and empty text strings, is true.

Note that Ruby uses elsif after if, not else if and not elif.

if Modifier

Example:

print "debug\n" if $DEBUG

Syntax:

expr if expr

Evaluates and returns the result of the expression on the left if the condition on the right is true. If the condition is not in effect, returns nil.

unless

Example:

unless baby?
  feed_meat
else
  feed_milk
end

Syntax:

unless expr [then]
  expr ...
[else
  expr ... ]
end

unless is the reverse of if; if the conditional expression is false, evaluates the expression beginning with then. elsif cannot be specified with unless.

unless Modifier

Example:

print "stop\n" unless valid(passwd)

Syntax:

expr unless expr

Evaluates and returns the result of the expression on the left if the condition on the right is false. If the condition is not in effect, returns nil.

case

Example:

case $age
when 0 .. 2
  "baby"
when 3 .. 6
  "little child"
when 7 .. 12
  "child"
when 13 .. 18
  "youth"
else
  "adult"
end

Syntax:

case expr
[when expr [, expr] ... [then]
  expr ..]..
[else
  expr ..]
end

case expressions execute branching for a single expression via matching. Comparisons of values specified in a when clause to the evaluated result of the first expression are performed by the === operator. When the values match, evaluates the contents of the when clause.

case returns the result of the last evaluated expression in a conditional when (or else) clause. If neither condition is in effect, returns nil.

Looping

while

Example:

ary = [0,2,4,8,16,32,64,128,256,512,1024]
i = 0
while i < ary.length
  print ary[i]
  i += 1
end

Syntax:

while expr [do]
   ...
end

Executes the contents of an expression as long as the expression remains true.

while returns nil. Alternatively, the while return value can also be the value of an argument to a break.

while Modifier

Example:

sleep(60) while io_not_ready?

Syntax:

expr while expr

Repeatedly executes the expression on the left as long as the expression on the right is evaluated as true. If the expression on the left is begin, while evaluates it first before looping.

The while modifier returns nil. Alternatively, the while modifier return value can also be the value of an argument to a break.

until

Example:

until f.eof?
  print f.gets
end

Syntax:

until expr [do]
   ...
end

Repeatedly executes the expression until it is evaluated as true.

until returns nil. Alternatively, the until return value can also be the value of an argument to a break.

until Modifier

Example:

print(f.gets) until f.eof?

Syntax:

expr until expr

Repeatedly executes the expression on the left until the expression on the right is evaluated as true. If the expression on the left is begin, the until modifier evaluates it first before looping.

The until modifier returns nil. Alternatively, the until modifier return value can also be the value of an argument to a break.

for

Example:

for i in [1, 2, 3]
  print i*2, "\n"
end

Syntax:

for lhs ...  in expr [do]
  expr ..
end

Repeatedly executes the contents for each evaluated object element. Approximately identical to the following:

(expr).each '{' '|' lhs..'|' expr .. '}'

It is only approximately identical because while blocks defined by do ... end or by { } introduce a new block scope for local variables, for has no effect on the scope of local variables.

for returns the return value of the each method for the objects specified in in.

break

Example:

i = 0
while i < 3
  print i, "\n"
  break
end

Syntax:

break [expr]

break escapes from the innermost loop. A "loop" is one of the following:

Unlike in C, break can only escape from loops. It does not exit from case.

for or an iterator that has escaped from a loop via break returns nil. However, if an argument is specified, the loop's return value will become that argument.

next

Example:

str.each_line do |line|
  next if line.empty?
  print line
end

Syntax:

next [expr]

next jumps to the next iteration of the innermost loop. In an iterator, next is an escape for a yield call.

A yield that has escaped via next returns nil. However, if an argument is specified, yield's return value will become that argument.

Exception Handling

raise

Examples:

raise
raise "you lose"
raise SyntaxError.new("invalid syntax")
raise SyntaxError, "invalid syntax"

Syntax:

raise
raise message
raise exception
raise error_type, message

Throws an exception. In the first format, throws the last exception again. In the second format, given a string argument, throws a RuntimeError exception with the given string as a message. In the third format, throws the exception if the argument is an exception object. In the last format, throws the exception specified in the first argument with the message given in the second argument.

Thrown exceptions can be trapped with a rescue clause in begin.

raise is not a reserved word in Ruby, but rather an built-in function.

begin

Example:

begin
  do_something
rescue
  recover
ensure
  must_do
end

Syntax::

begin
  expr ..
[rescue [error_type,..] [then]
  expr ..]..
[ensure
  expr ..]
end

If an exception is thrown while begin is being executed, a rescue clause can trap the exception; multiple clauses can be specified. If a rescue clause with a matching exception type exists, it is executed. The thrown exception can be referenced with the built-in variable $!.

When error_type is omitted, it traps all exceptions in the StandardError subclasses, of which most built-in exceptions in Ruby are members. See Built-in Exception Classes.

In rescue clauses, error_type is evaluated in the same way as an argument. If any value matches, the clause will be executed. If the value of error_type is not a class or a module, rescue throws a TypeError exception.

If there is an ensure clause, its contents are always evaluated immediately before a begin expression exits.

begin returns the result of the final argument evaluated in either its contents or in the rescue clause.

rescue Modifier

Example:

File.open("file") rescue print "can't open\n"

Syntax:

expr1 rescue expr2

When an exception is thrown in the first expression, evaluates the second expression. You cannot specify the exception class(es) to be trapped; in other words, you can only trap the subclasses of the StandardError exception class.

Expressions associated with the rescue modifier return expr1 if no exception is thrown and expr2 if an exception is thrown.

Method Exit

return

Example:

return
return 12
return 1,2,3

Syntax:

return [expr[',' expr ... ]]

Exits from a method with the return value. If two or more expressions are provided, the method's return value will consist of an array containing these values. If the expression is omitted, the return value will be nil.

Converted from CHM to HTML with chm2web Pro 2.85 (unicode)