Feature #12084



Added by sawa (Tsuyoshi Sawada) almost 6 years ago. Updated 2 days ago.

Target version:


For meta-programming/debugging purposes, I would like to request the inverse of Object#singleton_class. Namely, a method that is called on a class that is a singleton class, and returns the object it is a singleton of. Since the Singleton module in the standard library assigns the method name instance to such classes, I think Class#instance should be the name for such feature.

Array.singleton_class.instance # => Array
"foo".singleton_class.instance # => "foo"

When the receiver is a class but is not a singleton class, then it should raise an error.

Array.instance # => error

Related issues

Related to Ruby master - Feature #12655: Accessing the method visibilityFeedbackActions

Updated by justcolin (Colin Fulton) over 5 years ago

This feature would solve a lot of problems I had while doing what should have been simple meta-programming (if there is such a thing as "simple" meta-programming...).

Something to consider is what happens with nested singleton classes. Let's say you have this code:


Does that return Array or the first singleton class? I would think the former is more useful, but less obvious.

Actions #2

Updated by jeremyevans0 (Jeremy Evans) about 1 month ago

Updated by Eregon (Benoit Daloze) 3 days ago

#instance seems a too generic name for such a rarely-needed meta-programming feature, I think #singleton_instance is better.

justcolin (Colin Fulton) it would result in Array.singleton_class, otherwise that would break the invariant of #singleton_instance being the reverse of #singleton_class.

A concrete use-case would be welcome.

Updated by ufuk (Ufuk Kayserilioglu) 3 days ago

Agreed that instance is a bad name for this concept and we should not be basing the name on the Singleton class, since it is not the same kind of singleton in the singleton_class.

From what I understand this would be exposing the concept of "attached_object" to user code and that concept is clearly documented inside the CRuby source code to mean exactly this:

 *   - attached object: A singleton class knows its unique instance.
 *     The instance is called the attached object for the singleton class.

So a good name would be attached_object and its behaviour could be:

Array.singleton_class.attached_object # => Array
"foo".singleton_class.attached_object # => "foo"

Array.attached_object # => nil
"foo".attached_object # => nil

Updated by sawa (Tsuyoshi Sawada) 2 days ago

ufuk (Ufuk Kayserilioglu) wrote in #note-4:

Array.attached_object # => nil
"foo".attached_object # => nil

That clearly cannot be accepted as a feature because you would then have no way to distinguish whether the class's singleton object is nil or it does not have a singleton object. Note the following:

NilClass.instance # => nil

Also available in: Atom PDF