2012-05-12 75 views
2

与类名创建我需要做这样的事情Class实例变量红宝石

class Foo 
define perform() 
    puts 'hello' 
end 
end 

classname = 'Foo' 

instance = create_instance(classname) 
instance.perform(); 

是类似的东西可能。如果是这样的?

非常感谢!

回答

5

你可以使用const_get

instance = Object.const_get(classname).new 
instance.perform 
2

是的,这是possible-

class Foo 
    def perform 
    puts 'hello' 
    end 
end 

f = 'Foo' 

klass = Object.const_get f 

f.new.perform 
2

您可以使用Module#const_get

klass = Object.const_get(classname) 
instance = klass.new 

但你可能想第一白名单的类名,如果它的到来来自用户输入。否则,你可能会打开一个安全漏洞。