Dynamic decision on which class to use
- by Sirupsen
Hello,
Let's say I have a class named Klass, and a class called Klass2. Depending on the user's input, I'd like to decide whether I'll call "hello_world" on Klass, or 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
The user inputs "Klass2" and the script should say:
Hello World from Klass2!
Obviously this code doesn't work, since I'm calling #hello_world on String, but I'd like to call #hello_world on Klass2.
How do I "convert" the string into a referrence to Klass2 (or whatever the user might input), or how could I else would I achieve this behavior?