ruby类可以静态跟踪子类吗?
发布时间:2020-12-17 03:45:37 所属栏目:百科 来源:网络整理
导读:我的目标是: class MyBeautifulRubyClass #some code goes hereendputs MyBeautifulRubyClass.subclasses #returns 0class SlightlyUglierClass MyBeautifulRubyClassendputs MyBeautifulRubyClass.subclasses #returns 1 理想情况下甚至是地狱 puts MyBeau
我的目标是:
class MyBeautifulRubyClass #some code goes here end puts MyBeautifulRubyClass.subclasses #returns 0 class SlightlyUglierClass < MyBeautifulRubyClass end puts MyBeautifulRubyClass.subclasses #returns 1 理想情况下甚至是地狱 puts MyBeautifulRubyClass.getSubclasses #returns [SlightlyUglierClass] in class object form 我相信这是可能的,只是不确定如何! 解决方法
这是一种效率低下的方式:
Look up all descendants of a class in Ruby 有效的方法将使用继承的钩子: class Foo def self.descendants @descendants ||= [] end def self.inherited(descendant) descendants << descendant end end class Bar < Foo; end class Zip < Foo; end Foo.descendants #=> [Bar,Zip] 如果你需要知道后代的后代,你可以递归得到它们: class Foo def self.all_descendants descendants.inject([]) do |all,descendant| (all << descendant) + descendant.all_descendants end end end class Blah < Bar; end Foo.descendants #=> [Bar,Zip] Foo.all_descendants #=> [Bar,Blah,Zip] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |