Methods
suggest changeIntroduction
Methods in Ruby provide organized, reusable code to perform a set of actions. They simplify the coding process, prevent redundant logic, and make code easier to follow. This topic describes how to declare and call methods, including arguments, parameters, yield, and scope.
Remarks
A method is a named block of code, associated with one or more objects and generally identified by a list of parameters in addition to the name.
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. The value of the last expression evaluated in the method becomes the value of the method invocation expression.
hello("World")
# => "Hello, World"
When the receiver is not explicit, it is self.
self
# => main
self.hello("World")
# => "Hello, World"
As explained in the Ruby Programming Language book, many languages distinguish between functions, which have no associated object, and methods, which are invoked on a receiver object. Because Ruby is a purely object-oriented language, all methods are true methods and are associated with at least one object.
Overview of Method Parameters
| Type | Method signature | Call example | Assignments |
|---|---|---|---|
| Required | def fn(a, b, c) |
fn(2, 3, 5) |
a=2, b=3, c=5 |
| Variadic | def fn(*rest) |
fn(2, 3, 5) |
rest=[2, 3, 5] |
| Default | def fn(a=0, b=1) |
fn(2, 3) |
a=2, b=3 |
| Keyword | def fn(a: 0, b: 1) |
fn(a: 2, b: 3) |
a=2, b=3 |
These argument types can be combined. The minimum number of arguments equals the number of required arguments in the signature. A required parameter after *rest takes the last positional argument. Earlier extra positional arguments fill default parameters, then *rest.
| Type | Method signature | Call example | Assignments |
|---|---|---|---|
| R,D,V,R | def fn(a, b=1, *mid, z) |
fn(2, 97) |
a=2, b=1, mid=[], z=97 |
fn(2, 3, 97) |
a=2, b=3, mid=[], z=97 |
||
fn(2, 3, 5, 97) |
a=2, b=3, mid=[5], z=97 |
||
fn(2, 3, 5, 7, 97) |
a=2, b=3, mid=[5, 7], z=97 |
||
| R,K,K | def fn(a, g: 6, h: 7) |
fn(2) |
a=2, g=6, h=7 |
fn(2, h: 19) |
a=2, g=6, h=19 |
||
fn(2, g: 17, h: 19) |
a=2, g=17, h=19 |
||
| VK | def fn(**ks) |
fn(a: 2, g: 17, h: 19) |
ks={a: 2, g: 17, h: 19} |
fn(four: 4, five: 5) |
ks={four: 4, five: 5} |