liveBook · Manning

Method object

As explained in The Well-Grounded Rubyist, Fourth Edition

A Method object is a Ruby object that encapsulates a method bound to a receiver and can be invoked as executable behavior.

A Method object turns a method into a callable Ruby object that can be stored, passed around, and executed. Unlike a method name alone, it preserves the receiver to which the method is bound. section 14.1

class C
  def talk
    puts "Method-grabbing test!  self is #{self}."
  end
end
c = C.new
meth = c.method(:talk)

Capture an instance method with method(:talk). The resulting bound Method object remembers c as self, so meth.call executes talk on that particular instance. section 14.3.1

Method objects expose several useful distinctions:

  • Call a captured method with call, square brackets, or the dotted () form; each invokes the callable object. section 14.3.2
  • Inspect where a method was ultimately defined with owner, which helps when inheritance or mix-ins complicate method lookup. section 14.3.1
  • Detach a bound method with unbind, then bind it to an instance of the original class or a subclass. section 14.3.1
  • Obtain an unbound method directly from a class with instance_method, then bind it before calling it. section 14.3.1
  • Objectify methods made visible through method_missing when respond_to_missing? reports them as supported. section 15.1.1

Calling an inherited definition explicitly

For a subclass instance c, ordinary c.a_method uses the subclass definition. A.instance_method(:a_method).bind(c).call instead binds the superclass definition to c, allowing the original implementation to run with c as self. section 14.3.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains bound receivers, owners, unbinding, rebinding, direct unbound capture, and alternate invocation syntax.
Examples
Uses talk capture, owner inspection, subclass rebinding, explicit superclass dispatch, and dynamically exposed setter methods.
What it assumes
Assumes familiarity with Ruby methods, classes, instances, inheritance, and the distinction between callable objects.
What you can do after
Apply it via Ruby's method, unbind, instance_method, bind, and call operations to control executable behavior and receiver selection.
How it connects
Connects method objects with callable objects, Proc objects, lambdas, inheritance, mix-ins, method_missing, and respond_to_missing?.

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.