LoginSignup
0
2

More than 5 years have passed since last update.

Ruby の ObjectSpace を利用して、オブジェクト名からクラスオブジェクトを探す

Posted at

ブログ記事からの転載です。

Ruby で例えば "String" という文字列からその名前のクラスオブジェクトを取得したい場合があるとします。
そういう場合は ObjectSpace から逆算して検出することができます。

# クラスオブジェクトの一覧を取得する
classes =ObjectSpace.each_object(::Class)

# クラスオブジェクトの一覧から該当するクラスオブジェクトを探す
target = "String"
result = classes.find { |klass| klass.name == target }
p result == String
# => truk

また、Rails では String#constantize というメソッドが定義されており、上記と同等の機能があります。

"String".constantize   
# => String

[参照]

0
2
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
0
2