简体   繁体   English

我如何获得Ruby类的名称?

[英]How do I get the name of a Ruby class?

How can I get the class name from an ActiveRecord object? 如何从ActiveRecord对象获取类名?

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). 我只需要字符串中的类名(在本例中为User )。 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. 我知道这是非常基本的,但我搜索了Rails和Ruby的文档,我找不到它。

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

result.class.name

Here's the correct answer, extracted from comments by Daniel Rikowski and pseidemann. 这是正确答案,摘自Daniel Rikowski和pseidemann的评论。 I'm tired of having to weed through comments to find the right answer... 我厌倦了通过评论来寻找合适的答案......

If you use Rails (ActiveSupport): 如果您使用Rails(ActiveSupport):

result.class.name.demodulize

If you use POR (plain-ol-Ruby): 如果你使用POR(普通红宝石):

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. 如果要从类方法中获取类名,则class.nameself.class.name将不起作用。 These will just output Class , since the class of a class is Class . 这些只会输出Class ,因为类的类是Class Instead, you can just use name : 相反,您可以使用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 . 在我的情况下,当我使用类似result.class.name东西时,我得到了类似Module1::class_name东西。 But if we only want class_name , use 但是如果我们只想要class_name ,请使用

result.class.table_name.singularize

You can use class method for getting class of any object in ruby. 您可以使用class方法获取ruby中任何对象的类。

eg 例如

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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