Class from string

Let's say I have a class named Class and a class named Class 2 . Depending on the user input, I would like to decide if I call it "hello_world"

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 enters "Class 2" and the script should say:

Hello world from Klass2!

Obviously this code doesn't work as I #hello_world

am calling #hello_world

on String, but I would like to call on Klass2

.

How do I "convert" the string to a reference to Klass2

(or whatever the user can enter), or how could I achieve this?

+2


a source to share


3 answers


puts Object.const_get(class_to_use).hello_world

      



+11


a source


puts eval(class_to_use).hello_world

      



+1


a source


If you have ActiveSupport loaded (for example in a Rails app) you can also use #constantize:

class_to_use.constantize.hello_world

      

+1


a source







All Articles