gpt4 book ai didi

ruby - 在一个类和它的某个祖先之间定义的实例方法

转载 作者:数据小太阳 更新时间:2023-10-29 07:30:13 25 4
gpt4 key购买 nike

假设类 A 是类 B 的后代。获取 B 中定义的 A 的所有实例方法的列表(符号数组,顺序无关紧要)的最佳方法是什么,即 A 的实例方法 是在 B 或其任何子类上定义的吗?示例如下。其中类层次结构如下:

class C; def c; end end
class B < C; def b; end end
class D < B; def d; end end
class A < D; def a; end end

A 在各种类中的实例方法是:

A.instance_methods_within(Kernel) # =>  (Same as A.instance_methods)
A.instance_methods_within(C) # => [:a, :d, :b, :c]
A.instance_methods_within(B) # => [:a, :d, :b]
A.instance_methods_within(D) # => [:a, :d]
A.instance_methods_within(A) # => [:a] (Same as A.instance_methods(false))

最佳答案

这是我自己的解决方案。

class Class
def instance_methods_within klass
ancestors
.select{|k| k <= klass}
.inject([]){|a, k| a.concat(k.instance_methods(false))}
.uniq
end
end

Marc-André Lafortune 建议:

class Class
def instance_methods_within klass
ancestors
.select{|k| k <= klass}
.flat_map{|k| k.instance_methods(false)}
.uniq
end
end

关于ruby - 在一个类和它的某个祖先之间定义的实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22449757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com