简体   繁体   English

Ruby-有没有一种方法来获取本征类的实例?

[英]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. 我可以通过ObjectSpace来测试每个特征类,但是我认为它很昂贵。

Curiously, I must get the eigenclass of each object to test the match, because is_a? 奇怪的是,我必须获取每个对象的特征类来测试匹配项,因为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). 我希望有一个Class#instanceClass#instances方法来获取一个类(或本征类)的实例。

The most direct way would be extract the instance from the eigenclass' inspect , but I'm wondering if I can rely on it: 最直接的方法是从eigenclass's inspect提取实例,但是我想知道是否可以依靠它:

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: 我的用例是,我必须获取类方法的类,但是Method#owner给我本征类,而Method#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 : 如果要查找任何给定类的实例,可以使用ObjectSpace

class A; end
class B < A; end

ObjectSpace.each_object(A.singleton_class).to_a
# => [B, A]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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