rubyeigenclass

Can a Ruby object have multiple eigenclasses?


Eigenclasses are added into the inheritance hierarchy.

If multiple singleton methods are added, are these added to the same eigenclass, or different eigenclasses which are both injected into the inheritance hierarchy of that object?

For example

def foo.test
  0
end
def foo.test2
  0
end

Will this add 2 eigenclasses: one with a 'test' method, another with a 'test2' method? Or one eigenclass with both methods?


Solution

  • These are added to a single metaclass, because object always has only one singleton class.

    You can check it:

    foo.singleton_methods
    #=> [:test, :test2]
    foo.method(:test)
    #=> #<Method: #<Object:0x007ff9b4d48388>.test>
    foo.method(:test2)
    #=> #<Method: #<Object:0x007ff9b4d48388>.test2>
    

    Or using Method#owner:

    foo.method(:test).owner == foo.method(:test2).owner
    #=> true