2016-03-19 7 views
0

私は呼び出したいクラスの文字列表現を持っています。クラスは既に存在します。文字列(例: "Car")をRubyのクラスに変換する

klass = "Broseph" 
Class.new(Broseph) 
# => #<Class:0x007f9f0c1cc8b8> 
Class.new("Broseph") 
# => TypeError: superclass must be a Class (String given) 

文字列をクラスに変換するにはどうすればよいですか?文字列として表現したクラスのクラスメソッドをどのように呼び出すことができますか?また、そのクラスメソッドに引数を渡す必要があります。

答えて

2

あなたはconst_get使用することができます

klazz.some_method # when you know the method is fixed 
klazz.send('some_method') # when the method also is stored in a string 

klazz = Object.const_get('Broseph') 

次にようklazzのメソッドを呼び出します

関連する問題