Ruby: kind_of? vs. instance_of? vs. is_a?

Viewed 224406

What is the difference? When should I use which? Why are there so many of them?

5 Answers

https://stackoverflow.com/a/3893305/10392483 is a great explanation ... to add some more colour to this, I tend to use is_a? for "primatives" (String, Array, maybe Hash, etc.)

So "hello".is_a?(String), [].is_a?(Array), {}.is_a?(Hash)

For anything else, I tend to use instance_of? (Animal.new.instance_of?(Animal)

I say tend to because it's not quite that clear cut. Take for example:

class Animal;end

class Dog < Animal;end

x = Dog.new

x.is_a?(Dog) # => true
x.is_a?(Animal) # => true
x.instance_of?(Dog) # => true
x.instance_of?(Animal) # => false

As you can see, x is both a Dog and an Animal, but it's only an instance of Dog.

I see it as a question of specificity:

  • If I just want to know that it's an Animal and not a Plant I'll use is_a?
  • If I care that it's a Dog and not a Cat I'll use instance_of?

You can then take this further. If I care that it's a Sighthound and not a Bloodhound, assuming both are subclasses of Dog. Then I may want to make it even more specific.

That said, is_a?(Animal|Dog|Sighthound) will always work. But if you care about the specific subclass, instance_of? is always more specific.

Related