Bug #11064
open#singleton_methods for objects with special singleton_class returns an empty array
Description
def nil.bla
42
end
# works
nil.bla #=> 42
nil.singleton_method(:bla) #=> #<Method: NilClass#bla>
NilClass.instance_methods.include? :bla #=> true
# does not work
nil.singleton_methods #=> []
Updated by matz (Yukihiro Matsumoto) 4 months ago
nil
does not have its singleton class, but NilClass
plays the role of the singleton class (since nil
is the only instance of NilClass
).
So a singleton method definition defines a method in NilClass
. It's a kind of special treatment of singleton methods. Same for true
and false
.
We have several options:
- keep the behavior as it is, since
nil
does not have a singleton class -
nil.singleton_methods
should return methods defined inNilClass
(same forTrueClass
andFalseClass
)
Both have their own trade-offs. Either is OK for me but I slightly prefer the former, since it's easier.
Matz.
Updated by sawa (Tsuyoshi Sawada) 4 months ago
matz (Yukihiro Matsumoto) wrote in #note-1:
nil
does not have its singleton class, butNilClass
plays the role of the singleton class
I would appreciate it if @matz (Yukihiro Matsumoto) could kindly explain what the difference is between "being a singleton class" and "playing the role of a singleton class".
At the moment, I cannot understand at all how they are different. I am actually puzzled by a related comment by matz: https://bugs.ruby-lang.org/issues/12084#note-6. Why can we not simply say "NilClass
is the singleton class of nil
"?
Updated by Eregon (Benoit Daloze) 2 months ago
- Related to Bug #11063: Special singleton class should return true for singleton_class? test added