从Ruby对象访问singleton class是可以的:
some_object.singleton_class
是否可以进行反向操作:在singleton类中访问原始对象?
class << some_object
# how to reference some_object without actually typing some_object?
end
我想把这个method弄干:
class Example
PARENTS = []
class << PARENTS
FATHER = :father
MOTHER = :mother
PARENTS.push(FATHER, MOTHER)
end
end
并试图用更通用的东西替换类中的PARENTS
。
4条答案
按热度按时间n3ipq98p1#
我不知道任何内置的方法或关键字,但你可以写一个方法,将一个(单例)方法添加到对象的单例类中,返回对象本身:
用途:
在您的代码中:
在内部,YARV将对象存储在名为
__attached__
的示例变量中。示例变量没有通常的@
前缀,因此在Ruby中不可见或不可访问。这里有一个小的C扩展来暴露它:
用途:
yvt65v4c2#
只是出于好奇(请不要在家里或学校使用)
pzfprimi3#
我们可以这样做。
内嵌的拯救是处理直接对象
o
,它没有单例类。在MRI v2.7.0中,
微薄的收入
ma8fv8wu4#
Class#attached_object(Ruby 3.2+)
从
Ruby 3.2
开始,有一个Class#attached_object方法:返回接收者为单例类的对象。
如果类不是单例类,则引发TypeError。
例如:
来源: