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
I wanted to DRY this method:
class Example
PARENTS = []
class << PARENTS
FATHER = :father
MOTHER = :mother
PARENTS.push(FATHER, MOTHER)
end
end
and tried to replace PARENTS
inside the class with something more generic.
Starting from Ruby 3.2
, there is a Class#attached_object method:
Returns the object for which the receiver is the singleton class.
Raises an TypeError if the class is not a singleton class.
For example:
class Foo; end
Foo.singleton_class.attached_object #=> Foo
Foo.attached_object #=> TypeError: `Foo' is not a singleton class
Foo.new.singleton_class.attached_object #=> #<Foo:0x000000010491a370>
TrueClass.attached_object #=> TypeError: `TrueClass' is not a singleton class
NilClass.attached_object #=> TypeError: `NilClass' is not a singleton class
Sources: