How to convert string text to class name

I have a line like

classname = "Text" 

with this I want to create an object of class Text

Now when i try to do it

 classname = classname.constantize 

I get the text as a module, not as a class. Please suggest something.

Thank you and welcome

Rohit

+7
ruby
source share
5 answers

You can 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" 
+17
source share

Try it.

 Object.const_get("String") 

What will turn into β€œText” depends on your code. If it returns with a module, then Text is a module because you cannot have either a module or a class with the same name. Maybe there is a Text class in another module that you want to reference? It's hard to say more without knowing more about your code.

+3
source share
 classname = "Text" Object.const_set(classname, Class.new{def hello;"Hello"; end}) t = Object.const_get(classname).new puts t.hello # => Hello 

The trick is explained here: http://blog.rubybestpractices.com/posts/gregory/anonymous_class_hacks.html where the author uses it for a subclass of StandardError.

+2
source share

Try:

 Kernel.const_get "Text" 

For own modules:

 MyModule.const_get "Text" 
+1
source share

This will return a new classname object of class:

eval(classname).new

+1
source share

All Articles