How do I get the name of a Ruby class?

How can I get the class name from an ActiveRecord object?

I have:

result = User.find(1)

I tried:

# => User(id: integer, name: string ...)
# => #<User:0x3d07cdc>"

I need only the class name, in a string (User in this case). Is there a method for that?

I know this is pretty basic, but I searched both Rails' and Ruby's docs, and I couldn't find it.


You want to call .name on the object's class:

Here's the correct answer, extracted from comments by Daniel Rikowski and pseidemann. I'm tired of having to weed through comments to find the right answer...

If you use Rails (ActiveSupport):

If you use POR (plain-ol-Ruby):'::').last

Both result.class.to_s and work.

If you want to get a class name from inside a class method, or won't work. These will just output Class, since the class of a class is Class. Instead, you can just use name:

module Foo
  class Bar
    def self.say_name
      puts "I'm a #{name}!"



I'm a Foo::Bar!

In my case when I use something like I got something like Module1::class_name. But if we only want class_name, use


Need Your Help

Why isn't assertRaises catching my Attribute Error using python unittest?

python django unit-testing

I'm trying to run this test: self.assertRaises(AttributeError, branch[0].childrennodes), and branch[0] does not have an attribute childrennodes, so it should be throwing an AttributeError, which the

How to tell CMake where to put build files?

linux cmake

I want to tell CMake to output files and folders to a different folder instead of the current folder. I'm talking about the generated files by CMake below: