There are a some Ruby classes that don't allow singleton methods to be defined on their instances. For example, Symbol
:
var = :asymbol
def var.hello
"hello"
end
# TypeError: can't define singleton method "hello" for Symbol
I thought this might be a restriction on all immediate values, but it seems to work for nil
, true
, and false
(but not instances of Fixnum
or Bignum
):
var = true
def var.hello
"hello"
end
var.hello #=> "hello"
I don't understand why why Ruby allows singleton methods to be defined on certain classes of objects but not others.
Fixnum
s, but anyNumeric
.:fred
will always be the same symbol object, as will5
. Unfortunately, the same is true fortrue
, so it's something deeper than that; I'd wonder first if it's the same across versions, then wonder how each type's constancy was implemented.obj
isnil
,true
, orfalse
it returnsNilClass
,TrueClass
orFalseClass
, respectively. Ifobj
is aFixnum
or aSymbol
, it raises aTypeError
." As @Andrew notes, however, no numeric value can have a singleton class.nil
,true
andfalse
have singleton classes (e.g.,class << false; puts self; end #=> FalseClass
), but since those classes have only a single instance, there's no point to distinguish between the class and the singleton class.nil
has a singleton class for the same reason that it has instance methodsto_a
,to_c
,to_f
,to_h
,to_i
,to_r
andto_s
; namely, it allows for a soft landing when, for example, the receiver ofsingleton_class
could be eithernil
or something else. That logic does not extend totrue
andfalse
, however.