liveBook · Manning

Instance_method

As explained in The Well-Grounded Rubyist, Fourth Edition

instance_method is a Ruby class method that returns an unbound method object for an instance method.

Suppose `C` defines an instance method named `talk`. `C.instance_method(:talk)` captures that method without choosing a particular `C` object to receive it. The result is an unbound method object: it must be bound to an eligible object before it can be called. section 14.3.1

Capture, bind, and call

Given `class C; def talk; puts "self is #{self}"; end; end`, run `unbound = C.instance_method(:talk)`. Then `unbound.bind(C.new).call` executes `talk` with that new instance as `self`. An instance of a subclass of `C` can be used too. section 14.3.1

Contrast this with `c.method(:talk)`: that call captures a bound `Method` object whose receiver is already `c`. Calling it uses `c` as `self`. You could call `unbind` on that object, but `C.instance_method(:talk)` gets the unbound method directly from the class. Binding is restricted to an instance of `C` or one of its subclasses. section 14.3.1

The name reflects where `talk` is defined: an instance method is available to instances of its class, not just one object. That differs from a method defined on a particular object, and from a class method called on the class object itself. section 3.1.1 section 3.6.5

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Works through bound capture, unbinding, direct unbound capture, and binding restrictions; stops short of method-object implementation internals.
Examples
Uses `C#talk`, `c.method(:talk)`, `C.instance_method(:talk)`, and binding to an instance of subclass `D`.
What it assumes
Assumes familiarity with Ruby classes, instances, and method calls; explains bound versus unbound method objects through examples.
What you can do after
Practice/perform it: capture an unbound instance method, bind it to an eligible receiver, and call it.
How it connects
Connects instance methods with Method objects, unbound methods, receivers, inheritance, singleton methods, and class methods.

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.