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

Claudiu picture Claudiu · Oct 8, 2010 · Viewed 193k times · Source

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

Answer

sepp2k picture sepp2k · Oct 8, 2010

kind_of? and is_a? are synonymous.

instance_of? is different from the other two in that it only returns true if the object is an instance of that exact class, not a subclass.

Example:

  • "hello".is_a? Object and "hello".kind_of? Object return true because "hello" is a String and String is a subclass of Object.
  • However "hello".instance_of? Object returns false.