Question
How can I get the class name from an ActiveRecord object in Ruby?
For example:
result = User.find(1)
I tried:
result.class
# => User(id: integer, name: string ...)
result.to_s
# => "#<User:0x3d07cdc>"
I want only the class name as a string, such as "User" in this case. Is there a built-in method for that?
I know this is a basic question, but I could not find a clear answer in the Rails or Ruby documentation.
Short Answer
By the end of this page, you will understand how to get an object's class in Ruby, how to turn that class into a string, and how this works with ActiveRecord models such as User. You will also learn when to use class, name, and to_s, plus common mistakes beginners make.
Concept
In Ruby, every object knows what class it belongs to. When you call:
result.class
Ruby returns the class object for result, not just plain text. If result is a User, then result.class returns the User class.
If you need the class name as text, you can ask that class object for its name:
result.class.name
# => "User"
This matters because Ruby separates objects from their descriptions:
resultis an object instanceresult.classis the class objectresult.class.nameis the class name as a string
In Rails and ActiveRecord, this is especially useful when:
- logging object types
- building generic code
- debugging model instances
- writing reusable helpers
- checking behavior based on model type
A key idea is that class gives you the type itself, while name gives you the readable class name.
Mental Model
Think of an object like a specific employee badge, and the class like the job role printed on the badge.
- The object is one specific thing: a particular user record
- The class is its category:
User - The class name string is the text label:
"User"
So the flow is:
- Start with the object
- Ask what class it belongs to
- Ask that class for its name
Like this:
result # the badge
result.class # the role object
result.class.name # the printed role name
Syntax and Examples
The most common syntax is:
object.class.name
Example with ActiveRecord:
result = User.find(1)
result.class.name
# => "User"
Getting the class itself
result.class
# => User
This returns the class object, not a string.
Getting the class name as a string
result.class.name
# => "User"
Converting the class to a string
You may also see:
result.class.to_s
# => "User"
This also works in many normal cases, because the class object can be converted to text.
Beginner-friendly example
class Dog
end
pet = Dog.new
puts pet.class
# Dog
puts pet.class.name
# Dog
Explanation:
petis an instance ofDogpet.classreturns theDogclasspet.class.namereturns the string"Dog"
With different object types
puts 123.class.name
# => "Integer"
puts "hello".class.name
# => "String"
puts [1, 2, 3].class.name
# => "Array"
Step by Step Execution
Here is a small example:
result = User.find(1)
class_object = result.class
class_name = class_object.name
puts class_name
Step by step:
User.find(1)loads a user record from the database.- That record is stored in
result. result.classreturns the class objectUser.class_object.nameasks Ruby for the name of that class.- Ruby returns the string
"User". puts class_nameprintsUser.
You can also do it in one line:
puts result.class.name
Trace example with plain Ruby:
text = "hello"
text.class
# => String
text.class.name
# => "String"
Execution flow:
textcontains a string objecttext.classreturnsStringString.namereturns"String"
Real World Use Cases
Developers use class names in strings for many practical tasks.
Logging and debugging
logger.info("Loaded object type: #{result.class.name}")
This helps identify what kind of object your code is handling.
Generic helper methods
def print_type(record)
puts "Record type: #{record.class.name}"
end
Useful when a method can receive different model types.
Conditional behavior
case result.class.name
when "User"
puts "Handle user logic"
when "Admin"
puts "Handle admin logic"
end
Serialization or metadata
Sometimes apps include type names in output:
{
type: result.class.name,
id: result.id
}
Error reporting
raise "Expected User, got #{result.class.name}"
This makes errors easier to understand.
Real Codebase Usage
In real projects, developers often use this concept together with broader Ruby and Rails patterns.
Validation and guard clauses
def process_record(record)
raise ArgumentError, "Expected ActiveRecord object" if record.nil?
puts "Processing #{record.class.name}"
end
Polymorphic or shared code
A service object may accept different model instances:
def audit(record)
{
record_type: record.class.name,
record_id: record.id
}
end
Prefer behavior over type checks when possible
In Ruby, developers often avoid too many class-name checks and instead rely on shared methods.
Less flexible:
if record.class.name == "User"
record.send_welcome_email
end
Often better:
if record.respond_to?(:send_welcome_email)
record.send_welcome_email
end
Logging framework output
Rails.logger.debug("Saving #{record.class.name} with id=#{record.id}")
Namespaced classes
In larger codebases, class names may include modules:
Admin::User.name
# => "Admin::User"
This is important when working in Rails apps with namespaced models or service objects.
Common Mistakes
Mistake 1: Using to_s on the object itself
Broken example:
result = User.find(1)
result.to_s
# => "#<User:0x...>"
Why it happens:
to_shere is being called on the instance, not on the class- Ruby returns the object's string representation, not its class name
Use this instead:
result.class.name
# => "User"
Mistake 2: Expecting class to return a string
result.class
# => User
This returns a class object. If you need text, call name:
result.class.name
# => "User"
Mistake 3: Comparing class names as strings too often
This works:
result.class.name == "User"
But often this is better:
result.is_a?(User)
Why:
is_a?is clearer for type checks- it also works with inheritance
Mistake 4: Forgetting namespacing
module Admin
class User
end
end
Admin::User.name
# => "Admin::User"
If you expected just "User", this can surprise you.
Mistake 5: Using class-name checks when polymorphism is better
Instead of:
if record.class.name == "Invoice"
record.process
end
Often better:
record.process if record.respond_to?(:process)
Use type names only when they are actually needed.
Comparisons
| Expression | Returns | Type | Example Output |
|---|---|---|---|
result | the object instance | object | #<User:0x...> |
result.to_s | string form of the object | String | "#<User:0x...>" |
result.class | the object's class | Class | User |
result.class.name | the class name | String | "User" |
result.class.to_s | string version of the class | String | "User" |
result.is_a?(User) | whether object is a User | Boolean | true |
class.name vs class.to_s
| Option | Best use | Notes |
|---|---|---|
object.class.name | getting the class name explicitly | clearest and most readable |
object.class.to_s | converting class to text | usually works, but name better expresses intent |
class.name vs is_a?
| Goal | Better choice |
|---|---|
| Get the class name as text | object.class.name |
| Check whether an object is a certain type | object.is_a?(User) |
| Print useful debugging info | object.class.name |
| Handle inheritance safely | object.is_a?(ParentClass) |
Cheat Sheet
# Get the class object
object.class
# Get the class name as a string
object.class.name
# Also works in many cases
object.class.to_s
# Check type
object.is_a?(User)
Example
result = User.find(1)
result.class
# => User
result.class.name
# => "User"
Rules to remember
object.classreturns a class objectobject.class.namereturns the class name as a stringobject.to_sdoes not usually return the class name- Use
is_a?for type checks, not string comparison - Namespaced classes return full names like
"Admin::User"
Quick tip
If you want text, use:
object.class.name
FAQ
How do I get a Ruby class name as a string?
Use:
object.class.name
Example:
User.find(1).class.name
# => "User"
What does object.class return in Ruby?
It returns the object's class object, such as User, String, or Array.
Why does to_s not return "User" on my ActiveRecord object?
Because to_s is being called on the instance itself, not on its class. That produces an object representation like #<User:0x...>.
Is object.class.to_s valid in Ruby?
Yes, it usually returns the class name as a string. However, object.class.name is clearer.
How do I check if an object is a User?
Use:
object.is_a?(User)
This is better than comparing class names as strings.
Does this work for Rails ActiveRecord models?
Yes. ActiveRecord model instances are normal Ruby objects, so result.class.name works the same way.
What happens with namespaced classes in Ruby?
The full class name is returned.
Admin::User.name
# => "Admin::User"
Mini Project
Description
Build a small Ruby script that prints useful type information for different objects, including an ActiveRecord-style model object. This helps you practice the difference between an object itself, its class, and its class name as a string.
Goal
Create a script that shows the class object and class name string for several Ruby objects.
Requirements
- Create at least one custom Ruby class such as
User - Create instances of different object types
- Print each object's
class - Print each object's
class.name - Add one type check using
is_a?
Keep learning
Related questions
Add a Default Value to an Existing Column in a Rails Migration
Learn how to add or change a default value on an existing database column using Rails Active Record migrations safely.
Calling a Class Method from an Instance in Ruby
Learn how to call a class method from an instance in Ruby using self.class, with examples, pitfalls, and practical usage patterns.
Calling an Overridden Monkey-Patched Method in Ruby
Learn how to call the original method when monkey patching in Ruby, including alias_method patterns, examples, pitfalls, and practical usage.