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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…