liveBook · Manning

Is_a?

As explained in The Well-Grounded Rubyist, Fourth Edition

is_a? is a Ruby method that tests whether an object is an instance of a specified class or one of its subclasses.

is_a? checks whether an object belongs to a specified class or to one of that class’s ancestral classes. It follows Ruby’s inheritance hierarchy from specific classes toward general ones. section 3.8

>> mag = Magazine.new
=>  #<Magazine:0x000000012d972100>
>> mag.is_a?(Magazine)
=> true
>> mag.is_a?(Publication)
=> true

A Magazine instance reports true for both Magazine and its ancestor class Publication. section 3.8

Checking an inheritance relationship

If Magazine inherits from Publication, mag.is_a?(Magazine) and mag.is_a?(Publication) both return true. The test describes class ancestry, not every capability the object may acquire individually. section 3.8

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines class-ancestry testing and demonstrates it with a short example, without detailing method-dispatch internals.
Examples
Uses Magazine and Publication objects to test direct class and ancestral-class membership.
What it assumes
Assumes familiarity with Ruby objects and classes while grounding the test in inheritance relationships.
What you can do after
Evaluate whether an object belongs to a specified class hierarchy.
How it connects
Connects objects with classes, subclasses, superclasses, inheritance, and individually added methods.

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.