如何在 Ruby 的命名空间中获取所有类名? [英] How to get all class names in a namespace in Ruby?

查看:40
本文介绍了如何在 Ruby 的命名空间中获取所有类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模块 Foo,它是许多类的命名空间,例如 Foo::BarFoo::Baz 等等

I have a module Foo, that it is the namespace for many classes like Foo::Bar, Foo::Baz and so on.

有没有办法返回由 Foo 命名的所有类名?

Is there an way to return all class names namespaced by Foo?

推荐答案

Foo.constants

返回Foo 中的所有常量.这包括但不限于类名.如果你只想要类名,你可以使用

returns all constants in Foo. This includes, but is not limited to, classnames. If you want only class names, you can use

Foo.constants.select {|c| Foo.const_get(c).is_a? Class}

如果你想要类名和模块名,你可以使用 is_a?模块 而不是 is_a?类.

If you want class and module names, you can use is_a? Module instead of is_a? Class.

这篇关于如何在 Ruby 的命名空间中获取所有类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆