Question
What does class << self do in Ruby?
I want to understand what this Ruby idiom means, how it works, and when it should be used. For example, what is happening in code like this?
class Example
class << self
def greet
"hello"
end
end
end
How is this different from writing a class method in other Ruby styles?
Short Answer
By the end of this page, you will understand that class << self opens the singleton class of an object in Ruby. Inside that block, methods you define become methods on that specific object. When used inside a class body with self, it is a common way to define class methods. You will also see how it compares with def self.method_name, where it is useful in real code, and which beginner mistakes to avoid.
Concept
Ruby lets every object have its own private place to store methods that belong only to that object. That hidden place is called the singleton class (also called the eigenclass).
When you write:
class << self
# methods here
end
you are opening the singleton class of whatever self currently refers to.
Why this matters
In Ruby, classes are also objects. That means a class object can have its own methods.
For example:
- instance methods belong to instances of a class
- class methods belong to the class object itself
So inside a class definition:
class User
def name
"instance name"
end
end
name is an instance method. It is called on objects created from User.
But if you write:
class User
def .find
Mental Model
Think of every Ruby object as having:
- a main toolbox shared by all objects of its class
- a special personal toolbox just for itself
The singleton class is that personal toolbox.
If you open it with:
class << self
end
you are saying:
“Let me add methods to this object's personal toolbox.”
Now imagine a class like User.
User is itself an object. So User also has a personal toolbox. Methods added there become class methods.
- methods in the regular class body -> used by instances like
User.new - methods in the singleton class of
User-> used byUseritself
So the mental shortcut is:
- regular class body = methods for future objects
class << selfinside a class = methods for the class object now
Syntax and Examples
Core syntax
Defining a class method with def self.method_name
class Product
def self.count
42
end
end
puts Product.count
Defining the same thing with class << self
class Product
class << self
def count
42
end
end
end
puts Product.count
Both print:
42
Example: multiple class methods
class << self becomes especially useful when you want to define several class methods together.
class Calculator
<<
()
a + b
()
a * b
puts .add(, )
puts .multiply(, )
Step by Step Execution
Consider this code:
class Example
class << self
def greet
"hello"
end
end
end
puts Example.greet
Step-by-step
1. Ruby starts defining the class
class Example
Ruby creates or reopens the Example class object.
Inside this class body, self is Example.
2. Ruby sees class << self
class << self
Since self is Example, this is the same idea as:
class <<
Real World Use Cases
1. Grouping class methods in models or service classes
class Report
class << self
def daily
"daily report"
end
def weekly
"weekly report"
end
end
end
This keeps related class-level behavior together.
2. Private helper methods for class methods
class SlugGenerator
class << self
def generate(text)
normalize(text).downcase.gsub(" ", "-")
end
private
def normalize(text)
text.strip
end
end
end
This is useful when one class method needs helper methods that should not be public.
3. DSLs and framework internals
Ruby libraries often define behavior on classes themselves, not only on instances. For example:
Real Codebase Usage
In real Ruby projects, developers use class << self in a few common patterns.
Grouping class methods
Instead of repeating self. many times:
class User
def self.find(id)
# ...
end
def self.active
# ...
end
end
they may group them:
class User
class << self
def find(id)
# ...
end
def active
# ...
end
end
end
This is mostly a style choice when visibility is not involved.
Using private class methods
This is one of the strongest practical reasons to use it.
Common Mistakes
1. Thinking it always means “class methods”
This is only true when self is a class object.
name = "Ruby"
class << name
def excited
upcase + "!"
end
end
Here it adds a method to one string object, not to a class.
2. Confusing instance methods with class methods
Broken example:
class User
def greet
"hello"
end
end
User.greet
This fails because greet is an instance method.
Fix:
class User
def self.greet
"hello"
end
end
User.greet
Or:
Comparisons
class << self vs def self.method_name
| Style | Best for | Example | Notes |
|---|---|---|---|
def self.name | One or two class methods | def self.find; end | Short and easy to read |
class << self | Grouping many class methods | class << self; def find; end; end | Useful for shared visibility like private |
Instance methods vs class methods
| Type | Defined how | Called on |
|---|
Cheat Sheet
Quick reference
Define a class method
class User
def self.find
"found"
end
end
Same idea with class << self
class User
class << self
def find
"found"
end
end
end
What class << self means
- open the singleton class of
self - define methods on the current object
- inside a class body, that usually means class methods
Works on any object
obj = Object.new
class << obj
def special
"only for this object"
end
end
FAQ
What is class << self in Ruby?
It opens the singleton class of the current object. Inside that block, methods become methods of that object.
Is class << self the same as defining class methods?
Not exactly. It defines methods on the current object. Inside a class body, the current object is the class, so the result is class methods.
Is class << self the same as def self.method_name?
For defining class methods inside a class, they often produce the same result. class << self is more useful when grouping several methods or setting visibility.
Why would I use class << self instead of def self.method_name?
Use it when you want to define multiple class methods together or make some of them private.
Can I use class << self outside a class?
Yes. You can use class << object on any object to define methods only for that object.
What is a singleton class in Ruby?
It is a hidden class attached to one object. It stores methods that belong only to that object.
Does class << self create instance methods?
No. It creates methods on the current object's singleton class, not regular instance methods for all instances.
Mini Project
Description
Build a small Ruby utility class that converts text in different ways using class methods. This project demonstrates why class << self is useful for grouping multiple class methods and for keeping helper methods private.
Goal
Create a TextTools class with public class methods for formatting strings and a private class helper method used internally.
Requirements
- Create a class named
TextTools. - Use
class << selfto define at least two public class methods. - Add one private class helper method inside the same block.
- One method should title-case a string.
- Another method should create a URL-friendly slug from a string.
Keep learning
Related questions
How to Call Shell Commands from Ruby and Capture Output
Learn how to run shell commands in Ruby, capture output, check exit status, and choose the right method for scripts and apps.
How to Check Whether a String Contains a Substring in Ruby
Learn how to check if a string contains a substring in Ruby using include?, match, and multiline string examples.
How to Check if a Hash Key Exists in Ruby
Learn how to check whether a specific key exists in a Ruby hash using key?, has_key?, and include? with clear examples.