Dynamic decision on which class to use
Posted
by Sirupsen
on Stack Overflow
See other posts from Stack Overflow
or by Sirupsen
Published on 2010-05-11T13:53:54Z
Indexed on
2010/05/11
14:04 UTC
Read the original article
Hit count: 131
ruby
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?
© Stack Overflow or respective owner