const_get

クラスやモジュールの名前からクラスやモジュールそのものを取得したい時。

module Foo
  p const_get('String')
end

一見Stringという名前の定数が表示されるだけに見えるけど、

module Foo
  p const_get('String').new
end

クラス名というのは実は単なる定数で、そのままnewできてしまう。

File::Statみたいに入れ子になったものはどうすればいいのか。

module Foo
  # これはエラー
  p const_get('File::Stat').new('.')
end

そういう時はこうする。

module Foo
  p const_get('File')::const_get('Stat').new('.')
end
module Foo
  p File::const_get('Stat').new('.')
  p const_get('File')::Stat.new('.')
end

こうでもいい。

ちなみにconst_getはモジュールのメソッドなのでモジュールの中でやってるけど、

p Module.const_get('Array').new
p Class.const_get('Hash').new

モジュールの外ならこれでもいいし、

p String.const_get('File').const_get('Stat').new('.')

こんな意味不明なこともできる。