In this article, you will learn how to use the Ruby instance_of? method.
Using the instance_of? method
The instance_of? method is a built-in method in Ruby that allows you to check whether an object belongs to a specific class. This method is used to determine whether an object is an instance of a particular class or not.
Here, object is the object you want to check, and class is the class you want to compare it with.
str = "hello world" num = 10 puts str.instance_of?(String) # true puts num.instance_of?(Integer) # true puts str.instance_of?(Integer) # false
In this example, we have created two variables str and num, and then checked if they are instances of the String and Integer classes, respectively. The output will be true for both cases, since str is a string and num is an integer.
The instance_of? method differs from other type checking methods in Ruby, such as kind_of? and is_a?, in that it only returns true if the object is an instance of the specified class and not any of its subclasses.
class Parent end class Child < Parent end p = Parent.new c = Child.new puts p.instance_of?(Parent) # true puts c.instance_of?(Parent) # false puts c.instance_of?(Child) # true
In this example, we have created a Parent class and a Child class, where Child is a subclass of Parent. We have then created two objects p and c, and checked if they are instances of the Parent and Child classes. The output will be true for p.instance_of?(Parent), false for c.instance_of?(Parent), and true for c.instance_of?(Child).
It's important to note that the instance_of? method only works with classes, and not with modules or other objects.