クラス名の文字列からクラスを取得する方法

Ruby では、Module.const_get メソッドで、文字列からモジュールやクラスを取得できる。プラグイン機構をもつアプリを作るときに使えそうなので、メモしておく。

# coding: utf-8

class Hello
  def greet(name)
     puts "Hello, #{name}."
  end
end

# トップレベルに定義しているクラスなら、
# const_get でクラスを取得できる
hello = Module.const_get("Hello")
h = hello.new
h.greet "Kagawa"

module Greeting
  class Morning
    def greet(name)
      puts "Good morning, #{name}."
    end
  end
end

# モジュールの中に定義しているクラスの場合、
# const_get でまずモジュールを取得し、
# さらにモジュールの const_get でクラスを取得できる。
greeting = Module.const_get("Greeting")
morning = greeting.const_get("Morning")
m = morning.new
m.greet "Honda"

# モジュールが分かっているなら、
# const_get を直接呼び出してもいい。
Greeting.const_get("Morning").new.greet "Nagatomo"