Prev - DUP - Next - TOC

Methods


An explanation for `method' has still not been given. In this section it is presented.

In the case of OOPS, asking an object for any task, the object determines the processing for itself. The determined processing is called `method'.

In ruby, the invoking method of an object, (as it appeared many time before, you see) is formed like the following:

 ruby> "abcdef".length
 6

This example means that the method named `length' of the String object "abcdef" is called.

Since each determination of the method from its called name is achieved on execution, the process may be variant depending on the content of the variable.

 ruby> foo = "abc"
 "abc"
 ruby> foo.length
 3
 ruby> foo = [1, 2]
 [1, 2]
 ruby> foo.length
 2

The internal processes of obtaining the length are different between strings and arrays, even in such situations ruby determines the suitable process automatically. This feature of OOPL is called polymorphism. When an object receives unknown method an error raises.

 ruby> foo = 5
 5
 ruby> foo.length
 ERR: undefined method `length' for 5(Fixnum)

So the user need know what methods are acceptable to the object, but it isn't necessary to know how the methods are processed.

If some arguments are specified, they are surrounded by parentheses. For example:

 object.method(arg1, arg2)

The parentheses can be omitted unless ambiguous. In case of the above example,

 object.method arg1, arg2

means as same as the parenthesized case.

There is a special variable `self' in ruby, it is the object which call method. Callings method to self are used very often so an abbreviation are available. `self' in

 self.method_name(args...)

can be omitted then

 method_name(args...)

causes same effect. What we called fuction is just this abbreviation for method calling to self. Because of this ruby is called a pure object oriented language.

Though, functional methods behave quite similarly to the functions in other programming languages for the benefit of those who do not grok how everything is a method.


Prev - DUP - Next - TOC