检索类和类实例的“种类”

时间:2011-07-27 09:44:10

标签: ruby-on-rails ruby ruby-on-rails-3 class instance

我正在使用Ruby on Rails 3.0.9,我想检查对象是类还是类实例。例如,如果我有

Article  # It is a class name
@article # It is an instance of the Article class

也许我可能会做以下事情:

kind?(Article)  # => class
kind?(@article) # => class_instance

如何检索该信息?

2 个答案:

答案 0 :(得分:3)

Object有一个名为class的方法:

@article.class # => Article

还有kind_of?

if @article.kind_of? Class
   # class type
elsif @article.kind_of? Article
   # other type
end

答案 1 :(得分:1)

类是类Class的对象:

class A
end

Class === A       #=> true
Class === A.new   #=> false
A === A.new       #=> true

A.new这是类A

的对象