加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby – 在类中获取非祖先方法的数组

发布时间:2020-12-16 21:44:53 所属栏目:百科 来源:网络整理
导读:我想创建一个类,它有一种方法可以调用不在超类中的所有其他方法. 有没有办法我可以使用obj.methods来获得非祖先的方法?还是有另一种方法来做到这一点. 谢谢 解决方法 我不知道你在这里真正想做什么,也不知道“全部”是什么方法,但是如果问题是你如何弄清楚
我想创建一个类,它有一种方法可以调用不在超类中的所有其他方法.

有没有办法我可以使用obj.methods来获得非祖先的方法?还是有另一种方法来做到这一点.

谢谢

解决方法

我不知道你在这里真正想做什么,也不知道“全部”是什么方法,但是如果问题是你如何弄清楚一个类的实例方法是不是被继承的,那么.instance_methods的组合和.ancestors可以得到你的信息.在这里,使用Array作为示例类:
Array.instance_methods.sort                                                                         
=> ["&","*","+","-","<<","<=>","==","===","=~","[]","[]=","__id__","__send__","all?","any?","assoc","at","class","clear","clone","collect","collect!","compact","compact!","concat","delete","delete_at","delete_if","detect","display","dup","each","each_index","each_with_index","empty?","entries","eql?","equal?","extend","fetch","fill","find","find_all","first","flatten","flatten!","freeze","frozen?","grep","hash","id","include?","index","indexes","indices","inject","insert","inspect","instance_eval","instance_of?","instance_variable_get","instance_variable_set","instance_variables","is_a?","join","kind_of?","last","length","map","map!","max","member?","method","methods","min","nil?","nitems","object_id","pack","partition","pop","private_methods","protected_methods","public_methods","push","rassoc","reject","reject!","replace","respond_to?","reverse","reverse!","reverse_each","rindex","select","send","shift","singleton_methods","size","slice","slice!","sort","sort!","sort_by","taint","tainted?","to_a","to_ary","to_s","transpose","type","uniq","uniq!","unshift","untaint","values_at","zip","|"]

Array.ancestors
=> [Array,Enumerable,Object,Kernel]

Array.instance_methods.sort - Array.ancestors.map {|a| a == Array ? [] : a.instance_methods}.flatten
=> ["&","|"]

如果你只是想排除超类的方法,而不是包含的方法,那么还有.superclass.

Array.superclass
=> Object

Array.instance_methods.sort - Array.superclass.instance_methods
=> ["&","|"]

这有帮助吗

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读