从单例类中检索Ruby对象? [英] Retrieve a Ruby object from its singleton class?
问题描述
可以从Ruby访问单个类对象:
It is possible to access a singleton class from a Ruby object with:
some_object.singleton_class
是否可以执行相反的操作:在单例类内部时访问原始对象?
Is it possible to do the reverse operation : access the original object when inside the singleton class?
class << some_object
# how to reference some_object without actually typing some_object?
end
我想干燥此方法:
class Example
PARENTS = []
class << PARENTS
FATHER = :father
MOTHER = :mother
PARENTS.push(FATHER, MOTHER)
end
end
,并尝试用更通用的内容替换类中的PARENTS
.
and tried to replace PARENTS
inside the class with something more generic.
推荐答案
我不知道任何内置方法或关键字,但是您可以编写一个将(singleton)方法添加到对象的singleton类的方法,返回对象本身:
I'm not aware of any built-in method or keyword but you could write a method that adds a (singleton) method to an object's singleton class, returning the object itself:
class Object
def define_instance_accessor(method_name = :instance)
singleton_class.define_singleton_method(method_name, &method(:itself))
end
end
用法:
obj = Object.new #=> #<Object:0x00007ff58e8742f0>
obj.define_instance_accessor
obj.singleton_class.instance #=> #<Object:0x00007ff58e8742f0>
在您的代码中:
class Example
PARENTS = []
PARENTS.define_instance_accessor
class << PARENTS
FATHER = :father
MOTHER = :mother
instance.push(FATHER, MOTHER)
end
end
在内部,YARV将对象存储在名为__attached__
的实例变量中.实例变量没有通常的@
前缀,因此在Ruby中是不可见或不可访问的.
Internally, YARV stores the object in an instance variable called __attached__
. The instance variable doesn't have the usual @
prefix, so it isn't visible or accessible from within Ruby.
这里有一个C扩展来公开它:
Here's a little C extension to expose it:
#include <ruby.h>
static VALUE
instance_accessor(VALUE klass)
{
return rb_ivar_get(klass, rb_intern("__attached__"));
}
void Init_instance_accessor()
{
rb_define_method(rb_cClass, "instance", instance_accessor, 0);
}
用法:
irb -r ./instance_accessor
> obj = Object.new
#=> #<Object:0x00007f94a11e1260>
> obj.singleton_class.instance
#=> #<Object:0x00007f94a11e1260>
>
这篇关于从单例类中检索Ruby对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!