Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.ruby > #6621

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

From Robert Klemme <shortcutter@googlemail.com>
Newsgroups comp.lang.ruby
Subject Re: Create instance of class. Class name stored in a string.
Date 2012-09-25 08:42 +0200
Message-ID <acd225Fp0miU1@mid.individual.net> (permalink)
References <d97fb22b-73b0-4461-b21d-2dce663839ab@googlegroups.com>

Show all headers | View raw


On 25.09.2012 02:17, shaw.cttk@gmail.com 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/

Back to comp.lang.ruby | Previous | NextPrevious in thread | Find similar


Thread

Create instance of class. Class name stored in a string. shaw.cttk@gmail.com - 2012-09-24 17:17 -0700
  Re: Create instance of class. Class name stored in a string. Robert Klemme <shortcutter@googlemail.com> - 2012-09-25 08:42 +0200

csiph-web