๐ŸŽ“ A1Learner
๐Ÿ”
0 of 28 lessons completed

Ruby Singleton Class

Every object has a class that belongs to that object alone. That hidden class is called its singleton class.

class << self opens the singleton class

Dog opens its singleton class with class << self. The motto method defined there belongs to Dog itself.

class Dog
  class << self
    def motto
      puts "Loyal and loud"
    end
  end
end
Dog.motto

The superclass of an instance singleton

A dog singleton class sits above Dog in the lookup path. Its superclass prints as the plain class name.

class Dog
end
dog = Dog.new
puts dog.singleton_class.superclass

One object opens its own singleton class

class << rex opens the singleton class of one dog only. The other dog answers false when asked about the trick method.

class Dog
end
rex = Dog.new
fido = Dog.new
class << rex
  def trick
    puts "Roll over"
  end
end
rex.trick
puts fido.respond_to?(:trick)

Example

class Cat
  class << self
    def sound
      puts "Meow in chorus"
    end
  end
end
cat = Cat.new
Cat.sound
puts cat.singleton_class.superclass

Key points

  • Every object has a singleton class of its own.
  • class << self inside a class opens the singleton class of that class.
  • A method defined inside class << self is a class method.
  • The singleton_class method names the singleton class of an object.
  • singleton_class.superclass of an instance gives its real class.

In this example, Cat defines sound inside class << self, so the class itself answers the call. The cat object then names its singleton class through singleton_class. The superclass of that singleton class prints as Cat, the real class of the object.

Note

These programs prove singleton classes with names and verdicts, never by printing one.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does dog.singleton_class.superclass give for a Dog object?