I have two classes with method tables used to implement an interpretive language. B is derived from A. I would like to have all of the methods in A’s method table appear in B’s, so that I only have to search one table. I have tried various means to expand A’s table within B’s, but haven’t arrived at one that works yet.
class A
MethodTable = {one: -> one}
def one
end
end
class B < A
MethodTable = {two: -> two}
def two
end
end
Something like this?
class A
SelfMethodTable = {one: ->(obj : A) { obj.one }}
MethodTable = SelfMethodTable
def one
1
end
end
class B < A
SelfMethodTable = {two: ->(obj : B) { obj.two }}
MethodTable = A::MethodTable.merge(SelfMethodTable)
def two
"a"
end
end
pp! A::MethodTable, B::MethodTable
# A::MethodTable # => {one: #<Proc(A, Int32):0x109a9c130>}
# B::MethodTable # => {one: #<Proc(A, Int32):0x109a9c130>, two: #<Proc(B, String):0x109a9c1e0>}
res = B::MethodTable[:one].call(B.new)
pp! res, typeof(res)
# res # => 1
# typeof(res) # => Int32
1 Like