Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 134 ยท Object-Oriented Ruby

Singleton Methods and the Singleton Class

Learn Ruby singleton methods, the singleton class (eigenclass), class << self, define_singleton_method and how class methods really work, with runnable examples and method lookup.

In most languages all objects of a class share exactly the same methods. Ruby is different: you can give one single object its own method, without touching its class. Such a method is called a singleton method. It is a small idea with a big consequence, because it is the mechanism behind class methods, extend, and much of the metaprogramming you meet in Ruby libraries.

When you give an object a private method of its own, Ruby needs somewhere to store it. That place is a hidden class attached to the object, called its singleton class (also known as the eigenclass or metaclass). In this lesson you will define singleton methods, peek into the singleton class, understand class << self, and see why def self.name inside a class body creates a class method.

Singleton methods on a single object

Ruby A method that belongs to one object only

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

def greeting.shout defines a method on the object greeting only. Its singleton_methods list is [:shout], while the equal-looking other has no such method, and the last line fails with main.rb:12:in '<main>': undefined method 'shout' for an instance of String (NoMethodError). Notice the difference between copies: dup creates a plain copy without singleton methods (the output is false), while clone keeps them (true). That detail matters in Copying Objects.

You can attach singleton methods to almost anything, but not to integers, floats or symbols: those are single shared values, so a per-object method makes no sense.

Ruby Which objects accept singleton methods (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first attempt prints can't define singleton, and the second ends with the same kind of TypeError. Strings, arrays, hashes and instances of your own classes are fine.

define_singleton_method

def obj.name is fine when you know the name while writing. When the name or body comes from data, use define_singleton_method, which takes a block and also captures local variables as a closure.

Ruby Generating singleton methods dynamically

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The block closes over value and counter, so each method remembers its own data. The result is an ad hoc object with a typed-looking interface. This is a common way to build small test doubles and configuration objects (define_method and Dynamic Methods).

The singleton class

Where does shout actually live? In the object's singleton class, which Ruby creates the first time it is needed and places at the very front of the object's method lookup chain. You can reach it with singleton_class.

Ruby Looking at the singleton class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The singleton class has whisper as its own instance method, and its superclass is String, so the lookup is: singleton class first, then String, then everything else. s.class still prints String, because class skips singleton classes. singleton_class? is true for the hidden class and false for String. This is why a singleton method overrides a class method of the same name for that one object.

Ruby A singleton method overrides the class's method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Inside a singleton method super calls the next method in the chain, which is the class's regular hello. The ancestors list begins with the singleton class itself (shown as #<Class:#<Greeter:0x...>>), then Greeter. Objects that never get singleton methods never create a singleton class, so it costs nothing until you use it.

extend: modules into the singleton class

You saw in Modules and Mixins that obj.extend(Mod) adds a module's methods to one object. Now you can see how: it is the same as including the module into the singleton class.

Ruby extend equals include in the singleton class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Both lines work the same, and only those two objects can greet. The third person created afterwards cannot. Because a.is_a?(Polite) is true, extended objects also pass type checks against the module. Extending per object is how decorators can be added at runtime without a wrapper class.

Class methods are singleton methods

Here is the surprising part: a class is an object, an instance of Class. A class method is simply a singleton method of that class object.

Ruby def self.name and def ClassName.name are the same

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Inside a class body self is the class, so def self.open means def Library.open: a singleton method on the object Library. All three styles end up in the same place, and the list shows [:audit, :close, :open]. The last line prints #<Class:Object>, because the singleton class of Library inherits from the singleton class of its superclass Object. That chain is why subclasses inherit class methods.

Ruby Class methods are inherited through singleton classes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Motorcycle.describe is found on Vehicle's singleton class, but calls wheels on its own receiver, so it picks up the override and prints Motorcycle has 2 wheels. The ancestors begin [#<Class:Motorcycle>, #<Class:Vehicle>, #<Class:Object>].

class << self

Writing self. in front of every class method gets tedious. class << self opens the singleton class so that everything inside is defined on it. It is also the only way to use private and attr_accessor for class-level code.

Ruby class << self with private helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first block defines class-level attr_accessor, public methods and a private method, all in one place. Compare it to Instance and Class Methods where instance variables on the class itself (@counter) are explained: those belong to the class object, not to its instances. The final call fails with main.rb:25:in '<main>': private method 'secret' called for class IdGenerator (NoMethodError).

The << in class << self is not an operator in the usual sense. It is special syntax meaning "open the singleton class of the expression on the right". You can use any object there: class << some_object defines singleton methods for some_object.

Practical uses

Factory and utility methods. Time.now, File.read and Array.new are all singleton methods of their classes.

The Singleton pattern. Make new private and hand out one shared instance. The standard library module Singleton does this for you (Observable, Singleton and Standard Patterns); the hand-written version appears in public, private and protected.

Module methods. def self.foo in a module is a singleton method on the module object; that is how Math.sqrt works.

Test doubles and tracing. Add a singleton method to one object to stub or record calls without changing the class.

Ruby Stubbing one object with a singleton method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Both clocks are Clock objects, but each has a behavior of its own. The report cannot tell the difference, which is duck typing at work (Duck Typing and Polymorphism).

Pitfalls

  • Surprising lookups. A singleton method wins over the class's methods, so debugging "why did this object behave differently" means checking obj.singleton_methods.
  • Marshal and copies. Objects with singleton methods cannot be dumped with Marshal.dump, and dup drops the methods while clone keeps them.
  • Overuse. Dozens of per-object methods make code hard to follow. Prefer a class, a Struct, or a module for repeated shapes.
  • Class variables. Singleton-level instance variables (@counter on the class) behave more predictably than @@counter class variables.
Ruby Marshal refuses objects with singleton methods (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The message is singleton can't be dumped. Remember it when you cache or copy objects deeply (Copying Objects).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a singleton method?

    def obj.name or define_singleton_method attaches a method to a single object, stored in its singleton class.
  2. 2. What does def self.create mean inside a class body?

    Inside a class body self is the class, and a class is an object, so this is a singleton method of the class.
  3. 3. What is the first object in the method lookup for an object that has singleton methods?

    The singleton class sits in front of the object's class, so singleton methods take precedence.
  4. 4. How do dup and clone treat singleton methods?

    clone copies the singleton class and frozen state; dup creates a plain copy without singleton methods.
  5. 5. What does class << self do inside a class body?

    It reopens the singleton class, which is where class methods live. You can also use private and attr_accessor inside it.

Summary

  • A singleton method belongs to a single object; define it with def obj.name or define_singleton_method.
  • Singleton methods live in the object's hidden singleton class (eigenclass), which comes first in method lookup.
  • extend is shorthand for including a module into the singleton class.
  • Class methods are singleton methods of the class object, and subclasses inherit them because singleton classes inherit from each other.
  • class << self opens the singleton class, which allows private and attr_accessor for class-level code.
  • Integers, floats and symbols cannot have singleton methods; objects with them cannot be marshaled, and dup drops them while clone keeps them.

Next: The Ruby Object Model