Class and Method Definitions

Class Definitions

Example:

class Foo < Super
  def test
     :
  end
     :
end

Syntax:

class identifier ['<' superclass ]
  expr ..
end

Defines a class. Class names are identifiers beginning with an uppercase letter.

Class definitions assign a class to a constant specified by an identifier (in Ruby, classes and objects together are one instance of the Class class.)

When a class is already defined, writing a class definition with the same class name will add to the existing class definition.

class Foo < Array
  def foo
  end
end

class Foo
  def bar
  end
end

In a class definition, self is that class itself; otherwise, it is no different than a top-level definition. Class definitions can contain arbitrary expressions that will be executed when the class is defined.

Class definitions can operate as nests. In the following example, there is absolutely no functional relationship (such as inheritance) between the outer class Foo and the inner class Bar, other than the fact that the constant Bar is Foo's inner constant Foo::Bar. Class nests group together semantically related classes into the outer class or module, and can be used to express an inclusion relationship.

class Foo
  class Bar
  end
end

Class definitions return the result of the last evaluated expression. If that expression does not return a value, the class definition returns nil.

Module Definitions

Example:

module Foo
  def test
     :
  end
     :
end

Syntax:

module identifier
  expr ..
end

Defines a module. Module names are identifiers beginning with an uppercase letter.

Module definitions assign a module to a constant specified by an identifier. In Ruby, classes and objects together are one instance of the Class class.)

When a module is already defined, writing a module definition with the same module name will add to the existing module definition.

Module definitions return the result of the last evaluated expression. If that expression does not return a value, the module definition returns nil.

Method Definitions

Example:

def fact(n)
  if n == 1 then
     1
  else
    n * fact(n-1)
  end
end

Syntax:

def methodname ['(' [arg ['=' default]] ... [',' '*' arg] ')']
  expr ..
[rescue [error_type,..] [then]
  expr ..]..
[ensure
  expr ..]
end

Defines a method. In other words, defines the method of a class or module if within the definition of that class or module. If top-level, defines methods that can be called from anywhere. This kind of method can be used like functions are in other scripting languages.

Method names can be normal identifiers or redefinable operators (==, +, -, and so on; see Operator Expressions.

When a default expression has been provided to a dummy argument, it becomes the default value when the actual argument is omitted through a method call. The default expression is evaluated at the time of the call and in the context of the method definition.

When the last dummy argument has a * immediately before it, the remaining actual arguments are all stored in this argument as an array.

Example:

# method with no argument. end omitted below
def foo
end

# method with arguments
def foo(arg, arg2)

# method with default argument
def foo(arg = nil)

# with everything
def foo(arg, arg2, arg3 = nil, *rest)

# operator format
def ==(other)
def +(other)
def *(other)

For method definition, each type of dummy argument can only be specified according to the following sequence. Any of these types of arguments can be omitted.

These method definitions have special formats:

# unary plus/minus
def +@
def -@

# element substitution
def foo=(value)             # obj.foo = value

# [] and []=
def [](key)                 # obj[key]
def []=(key, value)         # obj[key] = value
def []=(key, key2, value)   # obj[key, key2] = value

Furthermore, a begin expression as well as rescue and/or ensure clauses can be specified to trap exceptions when executing a method.

Method definition returns nil.

Method Evaluation

When a method is called, its expressions are evaluated in the following order:

Everything is evaluated in the method's context, including the argument's default expression.

The method's return value is the value passed to return. When return is not called, returns the value of the last evaluated expression in the method, before any ensure clause is executed.

Methods cannot be called before they are defined. For example:

foo
def foo
  print "foo\n"
end

Calling an undefined method throws a NameError exception.

Singleton-Method Definitions

Example:

def foo.test
  print "this is foo\n"
end

Syntax:

def expr '.' identifier ['(' [ argument ['=' default]] ... [',' '*' argument ]')']
  expr ..
[rescue [error_type,..] [then]
  expr ..]..
[else
  expr ..]
[ensure
  expr ..]
end

A singleton method belongs to a certain object and not to a class. Singleton-method definitions can be nested.

The singleton methods of a class carry over to its subclasses. In other words, they act like the class methods in other object-oriented languages.

Singleton-method definitions return nil.

Class Method Definitions

In Ruby, class methods are the methods specific to a class. Classes are also objects, so these specific methods can be defined like regular objects.

Therefore, when a method in a class object is defined in some way, that object becomes a class method. Specifically, these methods can be defined in the following way (as can modules):

# singleton method
class Hoge
  def Hoge.foo
  end
end

# can use outside class definition, too
def Hoge.bar
end

# even if the class name changes, you don't have to change the method
class Hoge
  def self.baz
  end
end

Definition Operations

alias

Example:

alias foo bar
alias :foo :bar

Syntax:

alias newmethod oldmethod

Assigns an alias to a method or global variable. Specifies an identifier or a Symbol as the method name (expressions like obj.method are not permitted). alias's argument performs no evaluation of method calls or the like.

An aliased method carries over that method definition, retaining it even if the original method is redefined. This can be used when you want to change the actions of a given method, then use the result of the original method in the redefined method.

# defining method "foo"
def foo
  "foo"
end

# setting alias (retracting method definition)
alias :_orig_foo :foo

# "foo" redefined (using the old definition)
def foo
  _orig_foo * 2
end

p foo  # => "foofoo"

alias returns nil.

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