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

S

shaw.cttk

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
 
R

Robert Klemme

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top