Determine Class from Eigenclass Determine Class from Eigenclass ruby ruby

Determine Class from Eigenclass


Use ObjectSpace.each_object passing it the singleton class to find all classes that match the given singleton class:

Klass = Class.newObjectSpace.each_object(Klass.singleton_class).to_a  #=> [Klass]

However, since a class’s singleton class inherits from its superclass’s singleton class, you’ll get multiple results if the class you’re trying to find has subclasses:

A = Class.newB = Class.new(A)B.singleton_class.ancestors.include?(A.singleton_class)  #=> truecandidates = ObjectSpace.each_object(A.singleton_class)candidates.to_a  #=> [A, B]

Fortunately, classes/modules are sortable by their place in the inheritance tree (same order ancestors gives). Since we know all the results must be part of the same inheritance tree, we can take the max to get the correct class:

candidates.sort.last  #=> AObjectSpace.each_object(B.singleton_class).max  #=> B


Refining @BroiSatse's answer in a ruby-implementation-agnostic way,

class A; endclass B < A; endclass C < A; endeigenclass = A.singleton_classObjectSpace.each_object(eigenclass).find do |klass|  klass.singleton_class == eigenclassend#=> A

This is also reliable when handling branches in subclass trees, the only reason why @Andrew Marshall's elegant answer doesn't work.


Use ObjectSpace:

e = class << 'foo'; self; endObjectSpace.each_object(e).first    #=> 'foo'

To get object from inside of eigenclass:

class << 'foo'  puts ObjectSpace.each_object(self).firstend#=> 'foo'