What is the difference? When should I use which? Why are there so many of them?
Ruby: kind_of? vs. instance_of? vs. is_a
inheritanceintrospectionruby
Related Topic
- C++ – Difference between private, public, and protected inheritance
- Ruby-on-rails – How to understand nil vs. empty vs. blank in Ruby
- Ruby – How to write a switch statement in Ruby
- Python – What are the differences between type() and isinstance()
- Ruby – Equivalent of “continue” in Ruby
- Ruby – attr_accessor in Ruby
- Scala: list.flatten: no implicit argument matching parameter type (Any) = > Iterable[Any] was found
Best Answer
kind_of?
andis_a?
are synonymous.instance_of?
is different from the other two in that it only returnstrue
if the object is an instance of that exact class, not a subclass.Example:
"hello".is_a? Object
and"hello".kind_of? Object
returntrue
because"hello"
is aString
andString
is a subclass ofObject
."hello".instance_of? Object
returnsfalse
.