2010-05-11 59 views
2

假設我有一個名爲的類Klass,以及一個名爲的類Klass2。根據用戶的輸入,我想決定我是否會在克拉斯稱"hello_world",或Klass2:字符串的類別

class Klass 
    def self.hello_world 
    "Hello World from Klass1!" 
    end 
end 

class Klass2 
    def self.hello_world 
    "Hello World from Klass2!" 
    end 
end 

input = gets.strip 
class_to_use = input 
puts class_to_use.send :hello_world 

用戶輸入「Klass2」和腳本應該說:

你好來自Klass2的世界!

顯然,這代碼不工作,因爲我號召字符串#hello_world,但我想打電話#hello_worldKlass2

我如何「轉換」字符串到Klass2(或任何用戶可能輸入)的引用,或者我怎麼能實現這種行爲?

回答

11
puts Object.const_get(class_to_use).hello_world 
+1

是更好地使用'Object.const_get'?我從來沒有用過它...... tks! :] – 2010-05-11 14:26:44

1
puts eval(class_to_use).hello_world 
+7

'eval'總是有點不安全,可以通過'const_get'來避免。另外,不需要使用'send',因爲我們已經知道我們會調用'hello_world'方法。 – 2010-05-11 14:55:50

+0

爲什麼它不安全?我刪除了「發送」...完全錯過了。謝謝。 – 2010-05-11 15:19:49

+1

@j:'eval'讓用戶運行任意的Ruby代碼。他們可以做的不僅僅是選課。 – 2010-05-11 15:30:50

1

如果你的ActiveSupport(在Rails應用程序例如)加載,你也可以使用#constantize:

class_to_use.constantize.hello_world 
相關問題