假设我有一个名为 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”,脚本应该说:
Hello World from Klass2!
显然这段代码不起作用,因为我在 String 上调用 #hello_world
,但我想在 Klass2< 上调用
.#hello_world
/
我如何将字符串“转换” 为对Klass2
的引用(或用户可能输入的任何内容),或者我怎样才能实现此行为?
最佳答案
puts Object.const_get(class_to_use).hello_world
关于ruby - 来自字符串的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2811253/