Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

ruby - Why can't singleton methods be defined on Symbols or Fixnums?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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, and nil, 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...