如何获取 Ruby 类的名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/826210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the name of a Ruby class?
提问by andi
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 (Userin this case). Is there a method for that?
我只需要一个字符串中的类名(User在这种情况下)。有什么方法吗?
I know this is pretty basic, but I searched both Rails' and Ruby's docs, and I couldn't find it.
我知道这是非常基本的,但我搜索了 Rails 和 Ruby 的文档,但找不到。
回答by Darren Hicks
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...
这是正确答案,摘自 Daniel Rikowski 和 pseidemann 的评论。我厌倦了必须通过评论来找到正确的答案......
If you use Rails (ActiveSupport):
如果您使用 Rails (ActiveSupport):
result.class.name.demodulize
If you use POR (plain-ol-Ruby):
如果您使用 POR (plain-ol-Ruby):
result.class.name.split('::').last
回答by tal
Both result.class.to_sand result.class.namework.
无论result.class.to_s和result.class.name工作。
回答by jayhendren
If you want to get a class name from inside a class method, class.nameor self.class.namewon't work. These will just output Class, since the class of a class is Class. Instead, you can just use name:
如果您想从类方法内部获取类名,class.name否则self.class.name将不起作用。这些只会输出Class,因为类的类是Class. 相反,您可以使用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!
回答by Chivorn Kouch
In my case when I use something like result.class.nameI got something like Module1::class_name. But if we only want class_name, use
在我的情况下,当我使用类似的东西时,result.class.name我得到了类似的东西Module1::class_name。但如果我们只想class_name,使用
result.class.table_name.singularize
result.class.table_name.singularize

