假設我有一個名爲的類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_world
上Klass2
。
我如何「轉換」字符串到Klass2
(或任何用戶可能輸入)的引用,或者我怎麼能實現這種行爲?
是更好地使用'Object.const_get'?我從來沒有用過它...... tks! :] – 2010-05-11 14:26:44