What is the difference? When should I use which? Why are there so many of them?
What is the difference? When should I use which? Why are there so many of them?
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:
Animal and not a Plant I'll use is_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.