来自字符串的类
假设我有一个名为Klass的类,还有一个名为Klass2的类。 根据用户的输入,我想决定是否在Klass或Klass2上调用"hello_world"
:
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!
显然这段代码不起作用,因为我在String上调用#hello_world
,但我想在#hello_world
上调用Klass2
。
如何将字符串“转换”为对Klass2
(或者用户可能输入的任何内容),或者我怎么能实现这种行为呢?
puts Object.const_get(class_to_use).hello_world
puts eval(class_to_use).hello_world
如果你加载了ActiveSupport(例如在Rails应用程序中),你也可以使用#constantize:
class_to_use.constantize.hello_world