Backo
Backo

Reputation: 18871

Retrieve the "kind" of a Class and Class Instance

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?

Upvotes: 2

Views: 110

Answers (2)

Victor Moroz
Victor Moroz

Reputation: 9225

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

Upvotes: 1

Jacob Relkin
Jacob Relkin

Reputation: 163228

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

Upvotes: 4

Related Questions