How to get the get the type of a subtype?


In situations where a class inherits from another class, is it possible to figure out the type of the subtyped class?

# Parent class
class Element
  getter contents
  def initialize(@contents : Array(String), @line : Int32, @position : Int32)

# Subtype of Element
class Paragraph < Element

# Subtype of Element
class H1 < Element

# Subtype of Element
class H2 < Element

elements = [] of Element

# Add some instances to an array
elements << ["Introduction"], 1, 1
elements << ["Sextion"], 1, 1
elements << ["Paragraph"], 1, 1

# Cycle through the array and check the type of each element in the array.
elements.each do |el|
  puts typeof(el)
  puts el.contents

In the last section of the code, in my elements.each the call to typeof returns Element for each of the elements.

What I’m trying to do is differentiate which element of the array is a Paragraph, which is a H1 etc…

Can use a case which under the hood is calling is_a? TYPE.

This is also where overloaded methods come in, where you would call the same method with el but the type restriction on the param makes it select the right method.

Also some docs that helped me with this.

1 Like

And there’s the class method, as in exp.class

1 Like

There we go! class is what i was looking for!

Thanks asterite