开发者

Fake a type-cast in Ruby?

开发者 https://www.devze.com 2023-01-07 21:38 出处:网络
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 t

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
0

精彩评论

暂无评论...
验证码 换一张
取 消