开发者

How do I convert a string text into a class name

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.co开发者_StackOverflownstantize

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

Thanks and regards

Rohit


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"


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.


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.


Try:

Kernel.const_get "Text"

For your own defined modules:

MyModule.const_get "Text"   


This would return a new object of class classname:

eval(classname).new

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜