Can a Ruby object have multiple eigenclasses?

61 Views Asked by At

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?

2

There are 2 best solutions below

1
On BEST ANSWER

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
0
On

They go to the same singleton class, which is pretty easy to verify yourself:

foo.singleton_class.instance_methods.grep(/test/)
#=> [:test, :test2]