Hello,
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)
end
end
# Subtype of Element
class Paragraph < Element
end
# Subtype of Element
class H1 < Element
end
# Subtype of Element
class H2 < Element
end
elements = [] of Element
# Add some instances to an array
elements << H1.new ["Introduction"], 1, 1
elements << H2.new ["Sextion"], 1, 1
elements << Paragraph.new ["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
end
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…