As we've seen throughout this book, a method is defined using the
keyword
def
.
Method names should begin with a lowercase
letter.
[You won't get an immediate error if you use an
uppercase letter, but when Ruby sees you calling the method, it
will first guess that it is a constant, not a method invocation, and
as a result it may parse the call incorrectly.] Methods that act as
queries are often named with a trailing ``
?
'', such as
instance_of?
. Methods that are ``dangerous,'' or modify the
receiver, might be named with a trailing ``
!
''. For instance,
String
provides both a
chop
and a
chop!
. The first one
returns a modified string; the second modifies the receiver in
place. ``
?
'' and ``
!
'' are the only weird characters allowed
as method name suffixes.
Now that we've specified a name for our new method, we may need to
declare some parameters.
These are simply a list of local variable
names in parentheses. Some sample method declarations are
def myNewMethod(arg1, arg2, arg3) # 3 arguments
# Code for the method would go here
end
def myOtherNewMethod # No arguments
# Code for the method would go here
end
|
Ruby lets you specify default values for a method's arguments---values
that will be used if the caller doesn't pass them explicitly. This is
done using the assignment operator.
def coolDude(arg1="Miles", arg2="Coltrane", arg3="Roach")
|
"#{arg1}, #{arg2}, #{arg3}."
|
end
|
|
coolDude
|
� |
"Miles, Coltrane, Roach."
|
coolDude("Bart")
|
� |
"Bart, Coltrane, Roach."
|
coolDude("Bart", "Elwood")
|
� |
"Bart, Elwood, Roach."
|
coolDude("Bart", "Elwood", "Linus")
|
� |
"Bart, Elwood, Linus."
|
The body of a method contains normal Ruby expressions, except that you may
not define an instance method, class, or module within a method. The
return value of a method is the value of the last expression executed,
or the result of an explicit
return
expression.