Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 212
sferik Avatar asked Dec 19 '12 22:12

sferik


1 Answers

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.

like image 183
PinnyM Avatar answered Oct 23 '22 01:10

PinnyM