Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 567
Claudiu Avatar asked Oct 08 '10 18:10

Claudiu


People also ask

What is IS_A in Ruby?

The is_a? method will return a true value if an object is a of the type given as a parameter OR if it inherits from the type given as a parameter. So in effect, you can use it to ask "is there going to be a method from a class which I can run on this object".

What is object class in Ruby?

Object is the default root of all Ruby objects. Object inherits from BasicObject which allows creating alternate object hierarchies. Methods on object are available to all classes unless explicitly overridden. Object mixes in the Kernel module, making the built-in kernel functions globally accessible.


1 Answers

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.
like image 195
sepp2k Avatar answered Sep 20 '22 01:09

sepp2k