Use ObjectSpace.each_object
passing it the singleton class to find all classes that match the given singleton class:
Klass = Class.new
ObjectSpace.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.new
B = Class.new(A)
B.singleton_class.ancestors.include?(A.singleton_class) #=> true
candidates = 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 #=> A
ObjectSpace.each_object(B.singleton_class).max #=> B