You call a method by specifying a receiver, the name of the method,
and optionally some parameters and an associated block.
connection.downloadMP3("jitterbug") { |p| showProgress(p) }
|
In this example, the object
connection
is the receiver,
downloadMP3
is the name of the method,
"jitterbug"
is
the parameter, and the stuff between the braces is the associated
block.
For class and module methods, the receiver will be the class or module
name.
File.size("testfile")
Math.sin(Math::PI/4)
|
If you omit the receiver, it defaults to
self
, the current
object.
self.id
|
� |
537794160
|
id
|
� |
537794160
|
self.type
|
� |
Object
|
type
|
� |
Object
|
This defaulting mechanism is how Ruby implements private
methods. Private methods may
not be called with a receiver, so
they must be methods available in the current object.
The optional parameters follow the method name. If there is no
ambiguity you can omit the parentheses around the argument list when
calling a method.
[Other Ruby documentation sometimes calls
these method calls without parentheses ``commands.''] However,
except in the simplest cases we don't recommend this---there are some
subtle problems that can trip you up.
[In particular, you
must use parentheses on a method call that is itself a
parameter to another method call (unless it is the last parameter).]
Our rule is simple: if there's any doubt, use parentheses.
a = obj.hash # Same as
a = obj.hash() # this.
obj.someMethod "Arg1", arg2, arg3 # Same thing as
obj.someMethod("Arg1", arg2, arg3) # with parentheses.
|