In Java, you can do instanceof
. Is there a Ruby equivalent?
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.
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With