Every object on the heap begins with two words: its flags and klass, a pointer to its class. The class holds a method table and a pointer to its superclass. To run kit.greet, Ruby follows klass and then the super pointers until a method table has greet. Modules join that chain – here is a class with both an included and a prepended one:
module Shouty
def greet = super.upcase + "!"
end
module Courteous
def greet = "please, " + super
end
class Pup
def greet = "hi"
end
class Kit < Pup
include Courteous
prepend Shouty
def greet = "kit says " + super
end
kit = Kit.new
[kit.greet, Kit.ancestors.first(5)]show_lookup(kit, :greet)Step through it. The search starts at Shouty, not at Kit: prepend put the module in front, and Kit's own methods moved one place down, into a hidden "origin" class. include did not copy Courteous into Kit either – it put a small proxy class, an iclass, into the chain right after Kit, pointing at the module's method table. The first hit wins; every super continues the search from there, which is how all four greets end up in one sentence.
And a method for one single object? It cannot go into Kit. Ruby makes a class just for this object – its singleton class – and puts it between the object and Kit:
def kit.greet = "only me: " + super
show_lookup(kit, :greet)
kit.greetkit.singleton_class answers it, and attached_object leads back. Class methods are the same trick: def self.create in a class puts the method into the singleton class of the class object. One more way to watch the chain is Method#super_method:
m = kit.method(:greet)
owners = []
while m
owners << m.owner
m = m.super_method
end
owners- The search itself, a loop along
RCLASS_SUPER:search_method0:1685. includemakes the iclass:include_modules_at:1977;prependmoves the class's methods to its origin:rb_prepend_module:2048.- The singleton class, made on first use:
rb_singleton_class:2915.
find_owner(obj, name) walks obj.singleton_class.ancestors and gives back the first module or class whose own method table has name – method_defined?(name, false) (the false: not inherited) or private_method_defined?(name, false). Ruby's own answer is obj.method(name).owner; yours must match it.def find_owner(obj, name)
obj.singleton_class.ancestors.each do |mod|
# the first mod whose own table has name
end
nil
end
find_owner(kit, :greet)