假设我有一个名为的类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