Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > Create instance of class. Class name stored in a string.

Reply
Thread Tools

Create instance of class. Class name stored in a string.

 
 
shaw.cttk@gmail.com
Guest
Posts: n/a
 
      09-25-2012
Hi, I'm super new in Ruby World, and got in trouble with that:

how do I call the 'new' method of a class I don't know the name? The name of the class is stored in a string.

something like:

arg1 = "RADIUS"
codec = arg1.new

I would like to create an instance of whatever class name is stored in arg1 string.

Thanks in advance.

-- sfim
 
Reply With Quote
 
 
 
 
Robert Klemme
Guest
Posts: n/a
 
      09-25-2012
On 25.09.2012 02:17, http://www.velocityreviews.com/forums/(E-Mail Removed) wrote:
> Hi, I'm super new in Ruby World, and got in trouble with that:
>
> how do I call the 'new' method of a class I don't know the name? The
> name of the class is stored in a string.
>
> something like:
>
> arg1 = "RADIUS" codec = arg1.new
>
> I would like to create an instance of whatever class name is stored
> in arg1 string.


The usual idiom which also works with nested names is like this:

cls = name.split('::').inject(Object) {|cl, part| cl.const_get part}

Now you can do

obj = cls.new

In your case it's sufficient to do

cls = Object.const_get(arg1) # "RADIUS"
codec = cls.new

Kind regards

robert

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Don't understand behavior; instance form a class in another class'instance Martin P. Hellwig Python 1 03-26-2010 12:06 AM
Can you create an instance of a subclass with an existing instance of the base class? Sandra-24 Python 18 04-29-2006 04:01 PM
create an instance of a class that pointed to by interface of that class? Matt Java 10 04-07-2004 01:38 PM
converting base class instance to derived class instance Sridhar R Python 14 02-10-2004 02:47 PM
Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. DJ Dev ASP .Net 3 02-08-2004 04:19 PM



Advertisments