Question

How to Get a Ruby Class Name as a String

rubyruby-on-railsrails-activerecord

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:

  • result is an object instance
  • result.class is the class object
  • result.class.name is 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:

  1. Start with the object
  2. Ask what class it belongs to
  3. Ask that class for its name

Like this:

result       # the badge
result.class # the role object
result.class.name # the printed role name
Take Quiz

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:

  • pet is an instance of Dog
  • pet.class returns the Dog class
  • pet.class.name returns 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:

  1. User.find(1) loads a user record from the database.
  2. That record is stored in result.
  3. result.class returns the class object User.
  4. class_object.name asks Ruby for the name of that class.
  5. Ruby returns the string "User".
  6. puts class_name prints User.

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:

  • text contains a string object
  • text.class returns String
  • String.name returns "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.

Take Quiz

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_s here 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

ExpressionReturnsTypeExample Output
resultthe object instanceobject#<User:0x...>
result.to_sstring form of the objectString"#<User:0x...>"
result.classthe object's classClassUser
result.class.namethe class nameString"User"
result.class.to_sstring version of the classString"User"
result.is_a?(User)whether object is a UserBooleantrue

class.name vs class.to_s

OptionBest useNotes
object.class.namegetting the class name explicitlyclearest and most readable
object.class.to_sconverting class to textusually works, but name better expresses intent

class.name vs is_a?

GoalBetter choice
Get the class name as textobject.class.name
Check whether an object is a certain typeobject.is_a?(User)
Print useful debugging infoobject.class.name
Handle inheritance safelyobject.is_a?(ParentClass)
Take Quiz

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.class returns a class object
  • object.class.name returns the class name as a string
  • object.to_s does 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"
Take Quiz

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?
Take Quiz

Keep learning

Related questions

View more