简体   繁体   中英

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:

result.class
# => User(id: integer, name: string ...)
result.to_s
# => #<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.

你想在对象的类上调用.name

result.class.name

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):

result.class.name.demodulize

If you use POR (plain-ol-Ruby):

result.class.name.split('::').last

result.class.to_sresult.class.name有效。

If you want to get a class name from inside a class method, class.name or self.class.name 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}!"
    end
  end
end

Foo::Bar.say_name

output:

I'm a Foo::Bar!

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

result.class.table_name.singularize

You can use class method for getting class of any object in ruby.

eg

     array= [] 
     => []
     array.class
     => Array

     hash = {}
     => {}
     hash.class
     => Hash

     string = 'This is String'
     => "This is String"
     string.class
     => String 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM