Sirupsen
Sirupsen

Reputation: 2115

Class from string

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?

Upvotes: 2

Views: 266

Answers (3)

severin
severin

Reputation: 10268

If you have ActiveSupport loaded (e.g. in a Rails app) you can also use #constantize:

class_to_use.constantize.hello_world

Upvotes: 1

Ju Nogueira
Ju Nogueira

Reputation: 8461

puts eval(class_to_use).hello_world

Upvotes: 1

Jörg W Mittag
Jörg W Mittag

Reputation: 369458

puts Object.const_get(class_to_use).hello_world

Upvotes: 11

Related Questions