Thursday, August 28, 2008

Ruby notes(2) - OO

Function

Definition
def method([arg1, ..., argn,..., *arg, &arg])
    statements
end
Singleton Method
def obj.method([arg1, ..., argn,..., *arg, &arg])
    statements [rescue [exception [, exception...]] [=>var] [then] code ]... [else code ] [ensure code] end

undef method    #make the method undefined.yield(expr...)    #execute the block passed in to current method.
super(expr...)    #execute the method in super class.
super                #execute the method in super class with current method's arguments are passed in.
yield
alias newmethodname oldmethodname
Method Invocation
(*) General
method ([param1 ...[, *param [, &param]]])
method [param1 ...[, *param [, &param]]]
obj.method([param1 ...[, *param [, &param]]])
obj.method [param1 ...[, *param [, &param]]])
obj::method([param1 ...[, *param [, &param]]])
obj::method [param1 ...[, *param [, &param]]]
(*) With blocks
methdo { |[var1 [, var2 ...]]|
    code
}
method do |[var1 [, var2 ...]]|
    code goes here
end
A block has its own local scope and code within a block can access local variables of outer scope.

Class

Definition
class classname [ < superclass]
    code
end

classname MUST be a constant instead of a global or local variable. Class definition introduces a new scope. In order for different definitions of the same class to be merged, one of the two conditions must be met:
(1) A class does not include superclass
(2) if a class definition includes superclass, superclass MUST match super class of previous declaration.

class << object
    code
end

Creation
Instances of a class are created by using method new.
str = String.new or str = String::new

Modules

Definition
module modulename
    code
end
modulename MUST be a constant instead of a global or local variable. Module definition introduces a new scope. Different definitions of the same module are merged.