Project

General

Profile

Feature #12084

`Class#instance`

Added by sawa (Tsuyoshi Sawada) about 1 year ago. Updated about 1 year ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:73878]

Description

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 http://ruby-doc.org/stdlib-2.3.0/libdoc/singleton/rdoc/Singleton.html 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

History

#1 [ruby-core:74251] Updated by justcolin (Colin Fulton) about 1 year 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:

Array.singleton_class
     .singleton_class
     .instance

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

Also available in: Atom PDF