Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

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

26 views
Skip to first unread message

shaw...@gmail.com

unread,
Sep 24, 2012, 8:17:32 PM9/24/12
to
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

Robert Klemme

unread,
Sep 25, 2012, 2:42:10 AM9/25/12
to
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/
0 new messages