Skip to content
Singleton Methods and the Eigenclass
step 1/5

Reading — step 1 of 5

Learn

~1 min readSingletons and Reflection

In Ruby, you can attach a method to a SINGLE object instance:

s = "hello"

def s.shout
  upcase + "!"
end

s.shout            # "HELLO!"
"world".shout      # NoMethodError — only s has it

These are singleton methods. Behind the scenes, Ruby creates a hidden class — the eigenclass (also called singleton class or metaclass) — that lives between the object and its real class.

Lookup order for obj.method:

  1. obj's eigenclass
  2. obj's class
  3. obj's class's mixins
  4. obj's class's parent
  5. ...up to BasicObject
  6. method_missing fallback

Class methods are singleton methods on the class object:

class User
  def self.find(id)         # "def self.x" defines a singleton on User
    # ...
  end
end

# Equivalent:
User.singleton_class.define_method(:find) do |id|
  # ...
end

class << obj syntax opens the eigenclass:

class User
  class << self           # opens User's eigenclass — i.e., "all class methods"
    def find(id)
      # ...
    end
    def create(attrs)
      # ...
    end
  end
end

Clean way to declare multiple class methods in one block.

Use cases:

  • Class methods (Ruby's static methods)
  • Per-instance customization (rare in app code, common in test mocks)
  • Object#extend adds module methods to a single instance:
module Greeter
  def hello; "hi #{name}"; end
end

user = User.new(name: "Ada")
user.extend(Greeter)
user.hello              # "hi Ada"

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…