Message Propagation with Singleton Class

suggest change

Instances do not store methods; they carry data. A singleton class can hold methods for one object, including an ordinary instance.

When a message is sent, Ruby checks that object's singleton class first, if one exists. Otherwise it walks the ancestor chain of the object's class.

class Example
  def foo
    :example
  end
end

Example.new.foo #=> :example

module PrependedModule
  def foo
    :prepend
  end
end

class Example
  prepend PrependedModule
end

Example.ancestors #=> [PrependedModule, Example, Object, Kernel, BasicObject]
e = Example.new
e.foo #=> :prepend

def e.foo
  :singleton
end

e.foo #=> :singleton

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents