Ruby - is_a? v instance_of? - what is the difference?
Archive - Originally posted on "The Horse's Mouth" - 2010-01-27 18:14:20 - Graham EllisIn Ruby, have you ever wanted to know if an object is of a particular type?
The instance_of? method will return a true value if an object is of the type given as a parameter. However, instance_of? will return a false if we use it to check whether an object inherits from another class. So it's an exact check on the class name.
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".
Some sample code:
glug.each do |current|
puts current.bright, current.sides, current.area
puts current.class
puts current.instance_of?(Shape)
puts current.is_a?(Shape)
endIf the objects in the array glug are of type "Box" and "Circle" (which they were on today's Ruby Course), and boxes and circles inherit from Shapes, then the instance_of? calls will all return false, and the is_a? calls will return true.