0

I have the string representation of a class that I want to call. The class already exists.

klass = "Broseph"
Class.new(Broseph)
# => #<Class:0x007f9f0c1cc8b8>
Class.new("Broseph")
# => TypeError: superclass must be a Class (String given)

How can turn the string into a class? How can I call a class method on a class that I have represented as a string? I will also need to pass arguments to that class method.

sawa
  • 165,429
  • 45
  • 277
  • 381
Noah Clark
  • 8,101
  • 14
  • 74
  • 116

1 Answers1

2

You could use const_get:

klazz = Object.const_get('Broseph')

Then call methods on klazz like:

klazz.some_method # when you know the method is fixed
klazz.send('some_method') # when the method also is stored in a string
spickermann
  • 100,941
  • 9
  • 101
  • 131