What is a method? In OO programming, we don't think of operating on data directly from outside an object; rather, objects have some understanding of how to operate on themselves (when asked nicely to do so). You might say we pass messages to an object, and those messages will generally elicit some kind of an action or meaningful reply. This ought to happen without our necessarily knowing or caring how the object really works inside. The tasks we are allowed to ask an object to perform (or equivalently, the messages it understands) are that object's methods.
In ruby, we invoke a method of an object with dot notation (just as in C++ or Java). The object being talked to is named to the left of the dot.
Intuitively, this string object is being asked how long it
is. Technically, we are invoking the
Other objects may have a slightly different interpretation of
What we mean by length can vary depending on what object
we are talking about. The first time we ask
The thing to notice here is that an array knows something about what it means to be an array. Pieces of data in ruby carry such knowledge with them, so that the demands made on them can automatically be satisfied in the various appropriate ways. This relieves the programmer from the burden of memorizing a great many specific function names, because a relatively small number of method names, corresponding to concepts that we know how to express in natural language, can be applied to different kinds of data and the results will be what we expect. This feature of OO programming languages (which, IMHO, Java has done a poor job of exploiting) is called polymorphism.
When an object receives a message that it does not understand, an error is "raised":
So it is necessary to know what methods are acceptable to an object, though we need not know how the methods are processed.
If arguments are given to a method, they are generally surrounded by parentheses,
but they can be omitted if doing so does not cause ambiguity.
There is a special variable
is the same as
What we would think of traditionally as a function call is
just this abbreviated way of writing method invocations by