Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a variable is an instance of a class?

In Java, you can do instanceof. Is there a Ruby equivalent?

like image 544
NullVoxPopuli Avatar asked Aug 06 '10 14:08

NullVoxPopuli


People also ask

How do I find the class of an instance?

To get the class name of an instance in Python: Use the type() function and __name__ to get the type or class of the Object/Instance.

How do you check if a variable is a class type in Python?

Python has a built-in function called type() that helps you find the class type of the variable given as input. Python has a built-in function called isinstance() that compares the value with the type given. If the value and type given matches it will return true otherwise false.

How do I check if an object is an instance of a given class or of a subclass of it?

The isinstance() method checks whether an object is an instance of a class whereas issubclass() method asks whether one class is a subclass of another class (or other classes).


1 Answers

It's almost exactly the same. You can use Object's instance_of? method:

"a".instance_of? String # => true "a".instance_of? Object # => false 

Ruby also has the is_a? and kind_of? methods (these 2 are aliases, and work exactly the same), which returns true is one of the superclasses matches:

"a".is_a? String # => true "a".is_a? Object # => true 
like image 106
John Topley Avatar answered Oct 13 '22 06:10

John Topley