Methods are defined with the def
keyword, followed by the method name and an optional list of parameter names in parentheses. The Ruby code between def
and end
represents the body of the method.
def hello(name)
"Hello, #{name}"
end
A method invocation specifies the method name, the object on which it is to be invoked (sometimes called the receiver), and zero or more argument values that are assigned to the named method parameters.
hello("World")
# => "Hello, World"
When the receiver is not explicit, it is self
.
Parameter names can be used as variables within the method body, and the values of these named parameters come from the arguments to a method invocation.
hello("World")
# => "Hello, World"
hello("All")
# => "Hello, All"