Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a string text into a class name

Tags:

ruby

I have a string as

classname = "Text"

using this I want to create an object of the Text class

Now when I try doing this

classname = classname.constantize

I get the Text as a module and not as a class. Please suggest something.

Thanks and regards

Rohit

like image 524
Rohit Avatar asked Aug 26 '10 10:08

Rohit


1 Answers

You could use:

Object.const_get( class_name )

$ irb 
>> class Person 
>>     def name
>>         "Person instance"
>>     end
>> end
=> nil
>> class_name = "Person"
=> "Person"
>> Object.const_get( class_name ).new.name 
=> "Person instance"
like image 184
OscarRyz Avatar answered Sep 22 '22 23:09

OscarRyz