Given the following Ruby code, and given I have an instance of Klass, how can I call the do_stuff method on my Klass instance. I want to cast my Klass instance to Subklass. I understand type-casting this is not possible in Ruby – is there a way to fake it?
class Klass
...
end
class Subklass < Klass
...
def do_stuff
...
end
end
inst = Klass.new
inst.magically_convert_to_subklass_instance # Need help here
inst.do_stuff
Inheritance doesn’t work this way. If you have a Klass instance, you cannot cast it as Subklass in any way.
To share code like this you might better use a module to define the do_stuff method to append the features from the module into Klass.
i.e.: