Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

approve the class type of one object in rails

I have a simple question about rails syntax:

How can I find out to which class a object belongs?

I try to do someting like:

if class(object) == MyClass

Thanks Maechi

like image 377
Markus Avatar asked Jul 26 '10 19:07

Markus


2 Answers

object.is_a?(MyClass)
object.kind_of?(MyClass)

Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj. Aliased as ``


object.instance_of?(MyClass)
object.class == MyClass

Returns true if obj is an instance of the given class.


MyClass === object

Identical to is_a? method. Useful for case statements like

case object
when MyClass
when OtherClass
…
end
like image 54
tig Avatar answered Oct 04 '22 14:10

tig


You can do

if object.class == MyClass

or

if object.is_a?(MyClass)

The latter also returns true if object is an instance of a subclass of MyClass.

like image 44
sepp2k Avatar answered Oct 04 '22 12:10

sepp2k