2

If I have a class called "class User" is it possible to invoke the class via a String?

eg.

user = User.new (the normal way)

but I would like it to act this way

mystring = "User"
user = mystring.new
kidcapital
  • 5,064
  • 9
  • 46
  • 68

2 Answers2

5

Use the method const_get

my_string = "User"
user = Object.const_get(my_string).new
lcguida
  • 3,787
  • 2
  • 33
  • 56
1

I believe you can find the answer here: ruby convert class name in string to actual class

The above seems to be restricted to a method in Ruby on Rails, if you aren't using Rails you might want to look here: http://blog.andrewvc.com/quickly-constantize

The line of code the second link provides seems to work, just substitute the string at the beginning for your string, then if you call new on the result you can initialize the object by calling mystring.new (it doesn't seem to work for 'new mystring' though).

Community
  • 1
  • 1
cm92
  • 191
  • 1
  • 6