Singleton Classes in Ruby (aka eigenclasses)

Singleton methods in Ruby live in a special, hidden class called the singleton class (it used to be referred to as the eigenclass, but singleton class is the current term). Singleton methods are only available for a certain instance, so they can’t be defined in the regular class like all the other instance methods. Ruby methods can only be defined in class objects, so singleton methods also cannot be defined in a regular object with the instance variables. Thus, singleton classes.

The singleton class can be accessed with two different syntaxes:

class A; end
singleton_class = A.singleton_class
# OR
singleton_class2 = class << A
singleton_class == singleton_class2 # => true

Class methods in Ruby are really just singleton methods for the class object. The following example shows how to use the shovel operator to define singleton methods for a class.

class B
  def self.first
    "One singleton method"

  class << self
    def second
      "Another singleton method"

B.singleton_methods # => [:first, :second]

The rest of this blog post will refer to the singleton class of A as A’ (pronounced A prime).

Singleton classes inherit from other singleton classes. For example, if class B inherits from class A, B’ will inherit from A’ (remember, B’ stands for the singleton class of B and A’ stands for the singleton class of A).

class A
  class << self
    def whatever

class B < A; end

p B.whatever # => 'A.whatever'

One thought on “Singleton Classes in Ruby (aka eigenclasses)

  1. Pingback: Ruby Modules | Ruby/Rails Programming

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s