1

I am using Ruby on Rails 3.0.9 and I would like to check if a object is a class or a class instance. For example if I have

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

maybe I may do something like the following:

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

How can I retrieve that information?

Backo
  • 18,291
  • 27
  • 103
  • 170

2 Answers2

3

Object has a method called class:

@article.class # => Article

There's also kind_of?:

if @article.kind_of? Class
   # class type
elsif @article.kind_of? Article
   # other type
end
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
  • I don't want to retrieve the class name or something of similar. I want to check if a object is a class itself or it is a class instance. – Backo Jul 27 '11 at 09:49
  • I prefer to use `is_a?` instead of `kind_of?`, but that is just personal taste. – nathanvda Jul 27 '11 at 10:05
  • @Backo, Can you explain what you meant by _I want to check if a object is a class itself or it is a class instance_? – leenasn Jul 27 '11 at 10:13
  • leenasn - "I mean" a object is a class when it is stated as 'class Article ... end' and you use the 'Article' (*not* the String "Article" but something like "Article".constantize # => Article); "I mean" a object is a class instance when you initialize an instance of a class (for example @article = Article.new # => #
    - '@article' is the class instance).
    – Backo Jul 27 '11 at 11:17
1

Class is an object of class Class:

class A
end

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

A.new here is an object of class A

Victor Moroz
  • 9,167
  • 1
  • 19
  • 23