From: "ufuk (Ufuk Kayserilioglu)" <noreply@...>
Date: 2022-09-23T17:16:16+00:00
Subject: [ruby-core:110050] [Ruby master Feature#12084] `Class#instance`

Issue #12084 has been updated by ufuk (Ufuk Kayserilioglu).


Dan0042 (Daniel DeLorme) wrote in #note-12:
> I think it would be nicer if `#attached_object` returns nil instead of raising an error. Since nil can't be a valid return value anyway. So you don't need to check for `#singleton_class?` if you want to avoid the cost of Exceptions.

I have no problems with returning `nil` if that is desired, since, as you said, `nil` is never going to be a valid return value. However, I fear that people will see:
```ruby
NilClass.attached_object # => nil
nil.singleton_class # => NilClass 
```
and expect `NilClass.singleton_class?` to be `true`, but it is `false`. For that reason, raising an error felt safer.

Additionally, as I stated above, this is not meant to be an easy to use API for mass consumption, so terseness of the code that uses this method is not my primary concern. As in most reflection related APIs (looking at `const_source_location` and `autoload?`: https://bugs.ruby-lang.org/issues/17354) the usage can be complicated as long as it gets the job done.

@matz Do you have any opinions on the final state of this feature request?

----------------------------------------
Feature #12084: `Class#instance`
https://bugs.ruby-lang.org/issues/12084#change-99301

* Author: sawa (Tsuyoshi Sawada)
* Status: Open
* Priority: Normal
----------------------------------------
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.

~~~RUBY
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.

~~~RUBY
Array.instance # => error
~~~



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>