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
clas开发者_JAVA技巧s 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.:
module StuffModule
def do_stuff
print "do stuff"
end
end
class Klass
include StuffModule
end
inst = Klass.new
inst.do_stuff
精彩评论