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.
This has to do with a concept called ‘immediate values’ as described here by Matz.
In truth, no immediate values should permit a singleton method. However, in the case of
true,false, andnil, there are actually singleton classes that back these values (or the value is actually the singleton class – I’m not sure about this). You can therefore add singleton instances to the backing class which manifests as though it were the value itself. Numeric and Symbol instances are not singletons (obviously) and have nowhere to hold singleton methods.