The difference between Kind_of? / instance_of? / is_a? in Ruby

Asked 2 years ago, Updated 2 years ago, 127 views

I want to know how and when kind_of? / instance_of? / is_a? is different.

inheritance ruby

2022-09-21 15:40

1 Answers

kind_of? and is_a? are the same.

kind_of / is_a

Return true if class is a class of obj, or if class is a superclass of obj or a module included in < obj.

instance_of?

Returns true only when the object is exactly an instance of that class.(false in inheritance)

For example,

puts 5.is_a? Integer #true
puts 5.kind_of? Integer #true
puts 5.instance_of? Integer #false

Source - ruby-doc:

Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

Returns true if obj is an instance of the given class. See also Object#kind_of?.


2022-09-21 15:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.