tags:

views:

94

answers:

5

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

+1  A: 

Try:

Kernel.const_get "Text"

For your own defined modules:

MyModule.const_get "Text"   
floatless
+2  A: 

Try this.

Object.const_get("String")

What "Text" will get turned into depends on your code really. If it comes back with a module, then Text is a module, because you can't have both a module and a class with the same name. Maybe there's a Text class in another module you mean to refer to? It's hard to say more without knowing more about your code.

AboutRuby
+4  A: 

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"
OscarRyz
Thanks @OscarRyz and @Magnar this is working perfectly
Rohit
+2  A: 
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 to subclass StandardError.

steenslag
@steenslag what if the class is already defined somewhere else. The user inputs a string and according to that string you have to instantiate the appropriate class. Check the answer of @OscarRyz it gives me the perfect solution. Thanks.
Rohit
A: 

This would return a new object of class classname:

eval(classname).new

Tom Rossi