Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 找到模块的更好方法';谁的孩子?_Ruby_Metaprogramming - Fatal编程技术网

Ruby 找到模块的更好方法';谁的孩子?

Ruby 找到模块的更好方法';谁的孩子?,ruby,metaprogramming,Ruby,Metaprogramming,这就是我得到的,但它也可以找到类和其他常量。。有更好的办法吗 class Module def children constants.collect { |c| const_get(c) }.compact end end “children”似乎是指嵌套在给定模块下的模块,对吗?与继承关系无关 假设您只是指嵌套模块,那么以下功能应该可以工作: class Module def children constants.collect { |

这就是我得到的,但它也可以找到类和其他常量。。有更好的办法吗

class Module
    def children
        constants.collect { |c| const_get(c) }.compact
    end
end

“children”似乎是指嵌套在给定模块下的模块,对吗?与继承关系无关

假设您只是指嵌套模块,那么以下功能应该可以工作:

class Module
    def children
        constants.collect { |c| const_get(c) }.
            select { |m| m.instance_of?(Module) }
    end
end
编辑:您可能需要使用
常量(false)
来防止在继承链的更上层模块上进行常量查找