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
