Question

I am looking for a way to get the instance of an eigenclass, since each eigenclass has only one instance.

I could look thru ObjectSpace be testing each eigenclass, but I guess it's expensive.

Curiously, I must get the eigenclass of each object to test the match, because is_a? does not suffice:

class A; end
class B < A; end

AA = class << A; self; end

p A.is_a? AA #=> true
p B.is_a? AA #=> true!!!!

I wish there was an Class#instance or Class#instances method to get the instance(s) of a class (or eigenclass).

The most direct way would be extract the instance from the eigenclass' inspect, but I'm wondering if I can rely on it:

p AA         #=> #<Class:A>
instance = Object.const_get(AA.inspect.match(/^#<Class:(\w+)>$/)[1])
p instance   #=> A

# (this works for class' eigenclass)

My use case is that I must get the class of a class method, but the Method#owner gives me the eigenclass, and Method#receiver gives me the current receiver:

# Continuing previous example
def A.f; end
mtd = B.method(:f)
p mtd.owner     #=> #<Class:A>
p mtd.receiver  #=> B
# I want to obtain A

Any ideas?

Was it helpful?

Solution

If you want to find instances of any given class, you can use ObjectSpace:

class A; end
class B < A; end

ObjectSpace.each_object(A.singleton_class).to_a
# => [B, A]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top