LoginSignup
1
0

More than 5 years have passed since last update.

Rubyで定義されている全てのClassとModuleを取得する

Last updated at Posted at 2017-03-02
modules = ObjectSpace.each_object(Module).to_a

puts modules
puts modules.reject(&:singleton_class?) # 特異クラスを外す場合

公式のドキュメントのObjectSpaceから引用。

each_object(klass) -> Enumerator
指定された klass と Object#kind_of? の関係にある全てのオブジェクトに対して繰り返します。引数が省略された時には全てのオブジェクトに対して繰り返します。

上記のコードはRubyで定義されている全てのオブジェクトに対して kind_of?(Module) を実行しており、ClassとModuleに属するオブジェクトはこの判定式がtrueになるので、全てのClassとModuleが取得できます。

特異クラスを外したい場合は singleton_class? を実行して true を返すものを外します。

参考サイト

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0