Chapter 6. Methods, Procs, Lambdas, and Closures

image with no caption

A method is a named block of parameterized code associated with one or more objects. 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.

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. We have not covered class definitions in Ruby yet, so the example methods defined in this chapter look like global functions with no associated object. In fact, Ruby implicitly defines and invokes them as private methods of the Object class.

Methods are a fundamental part of Ruby’s syntax, but they are not values that Ruby programs can operate on. That is, Ruby’s methods are not objects in the way that strings, numbers, and arrays are. It is possible, however, to obtain a Method object that represents a given method, and we can invoke methods indirectly through Method objects.

Methods are not Ruby’s only form of parameterized executable code. Blocks, which we introduced in Blocks, are executable ...

Get The Ruby Programming Language now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.