liveBook · Manning

Method

As explained in The Well-Grounded Rubyist, Fourth Edition

A method definition is Ruby source code that declares the name, parameters, and executable behavior of a method.

A method definition is Ruby source code that declares a method’s name, parameters, and executable behavior. It gives an object an action that can later be requested through a method call. section 2.1.3 section 2.1.1

A parameterized conversion method

def obj.c2f(c) c * 9.0 / 5 + 32 end puts obj.c2f(100) # 212.0 Here, c is the formal parameter, while 100 is the argument supplied by the call. The method returns the value of its final expression. section 2.1.3

Parameters appear after the method name, usually in parentheses, and correspond positionally to arguments in the call. Parentheses may be omitted in simple definitions and calls, although keeping them can clarify chained or ambiguous expressions. Empty parentheses are valid for methods without arguments but are commonly omitted. section 2.1.3

Several Ruby mechanics shape how method definitions behave:

  • Every method call returns a value; a definition can use its final expression as that result. section 2.1.3
  • A method definition itself evaluates to the symbol naming the newly defined method, even when calling that method would return false. section 7.5.1
  • A top-level definition becomes a private instance method of Kernel and is therefore available as a bareword-style call to objects. section 5.5
  • Ruby can interpret a bare identifier as a local variable or method call; unresolved names raise a NameError. section 2.5.4
def obj.c2f(c)
  c * 9.0 / 5 + 32
end

Inspect the complete method definition used for the conversion example, including its receiver, parameter, body, and terminating end. section 2.1.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains parameters, calls, return values, syntax variations, name resolution, and visibility, while deferring class design.
Examples
Uses a Celsius-to-Fahrenheit converter, a greeting method, bareword calls, and an irb-style truth-value experiment.
What it assumes
Assumes basic objects and expressions while teaching parameters, arguments, returns, identifiers, self, scope, and visibility.
What you can do after
Build it from scratch by defining parameterized Ruby methods and calling them with matching arguments.
How it connects
Connects methods with objects, classes, method calls, parameters, arguments, scope, self, visibility, and local variables.

Also explained in

Compare how 20 books explain method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.