Name

def Statement

Synopsis

def method([arg..., arg=default..., *arg, &arg])
code
[rescue [exception_class[, exception_class...]] [=> variable] [then]
code]...
[else
code]
[ensure
code]
end

Defines a method. Arguments may include the following:

arg

Mandatory argument.

arg=default

Optional argument. If argument isn’t supplied by that which is calling the method, the default is assigned to arg. The default is evaluated at runtime.

*arg

If there are remaining actual arguments after assigning mandatory and optional arguments, they are assigned to arg as an array. If there is no remainder, empty array is assigned to arg.

&arg

If the method is invoked with a block, it is converted to a Proc object, then assigned to arg. Otherwise, nil is assigned.

Operators can also be specified as method names. For example:

def +(other)
  return self.value + other.value
end

You should specify +@ or -@ for a single plus or minus, respectively. As with a begin block, a method definition may end with rescue, else, and ensure clauses.

Get Ruby in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.