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
Usage:
obj = Object.new #=> #<Object:0x00007ff58e8742f0>
obj.define_instance_accessor
obj.singleton_class.instance #=> #<Object:0x00007ff58e8742f0>
In your code:
class Example
PARENTS = []
PARENTS.define_instance_accessor
class << PARENTS
FATHER = :father
MOTHER = :mother
instance.push(FATHER, MOTHER)
end
end
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.
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);
}
Usage:
irb -r ./instance_accessor
> obj = Object.new
#=> #<Object:0x00007f94a11e1260>
> obj.singleton_class.instance
#=> #<Object:0x00007f94a11e1260>
>
singleton_class?
so a singleton class is quite aware of its special status. – Goshsome_object
is a local variable, it's not defined in theclass << some_object
block. Attempting to reference it within the block results in aNameError
. – Gosh