简体   繁体   中英

Ruby - Is there a way to get the instance of an eigenclass?

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?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM