Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!eternal-september.org!feeder.eternal-september.org!newsfeed101.telia.com!starscream.dk.telia.net!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Robert Klemme Newsgroups: comp.lang.ruby Subject: Re: Create instance of class. Class name stored in a string. Date: Tue, 25 Sep 2012 08:42:10 +0200 Lines: 33 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net UsvSP4RlIjIjVOUTLpVxOwjXzd8nxEW35apOMFJuCTfWTA6hmzWZR2Bx4CTEPQh+A= Cancel-Lock: sha1:gAleNAvP/ToW4qb+BVT+6ral5a0= User-Agent: Mozilla/5.0 (Windows NT 6.0; WOW64; rv:15.0) Gecko/20120907 Thunderbird/15.0.1 In-Reply-To: Xref: csiph.com comp.lang.ruby:6621 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/