亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在Ruby中查找類的所有后代

在Ruby中查找類的所有后代

慕田峪9158850 2019-10-06 13:26:02
我可以輕松地提升Ruby中的類層次結構:String.ancestors     # [String, Enumerable, Comparable, Object, Kernel]Enumerable.ancestors # [Enumerable]Comparable.ancestors # [Comparable]Object.ancestors     # [Object, Kernel]Kernel.ancestors     # [Kernel]有什么辦法可以降低層次結構嗎?我想這樣做Animal.descendants      # [Dog, Cat, Human, ...]Dog.descendants         # [Labrador, GreatDane, Airedale, ...]Enumerable.descendants  # [String, Array, ...]但似乎沒有descendants方法。(出現這個問題是因為我想在一個來自基類的Rails應用程序中找到所有模型并列出它們;我有一個可以與任何此類模型一起使用的控制器,并且我希望能夠添加新模型無需修改控制器。)
查看完整描述

3 回答

?
慕森王

TA貢獻1777條經驗 獲得超3個贊

這是一個例子:


class Parent

  def self.descendants

    ObjectSpace.each_object(Class).select { |klass| klass < self }

  end

end


class Child < Parent

end


class GrandChild < Child

end


puts Parent.descendants

puts Child.descendants

放置Parent.descendants給您:


GrandChild

Child

把Child.descendants給你:


GrandChild


查看完整回答
反對 回復 2019-10-06
  • 3 回答
  • 0 關注
  • 672 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號