2

我想查找特定类中包含哪些模块,不包括其祖先。例如:

module M; end
module N; end

class A; include M; end
class B < A; include N; end

p B.included_modules

#=> [N, M, Kernel]
# I want only N

我无法使用B.included_modules[0],因为我不知道包含多少模块B

4

1 回答 1

3

如果你知道 A 是 B 的超类,那么

p B.included_modules - A.included_modules应该给你你正在寻找的东西

p B.included_modules - B.superclass.included_modules

module M; end
module N; end
module O; end

class A; include M; end
class B < A; include N; include O; end

p B.included_modules - A.included_modules
#=> [O, N]
于 2013-01-14T12:32:02.987 回答