From: Josh Cheek Date: 2011-01-29T05:53:32+09:00 Subject: Re: instantiating a class --0016361e847c298b6e049aee427e Content-Type: text/plain; charset=ISO-8859-1 On Fri, Jan 28, 2011 at 2:39 PM, Rick Tan wrote: > How do i instantiate a class whose name is contained in a variable ? > > For example > > Class myClass > end > > myVariable="myClass" > > So basically i like to use the content of myVariable to dictate which > class to instantiate, i.e. doing the same thing as myClass.new but let > myVariable determines which class i instantiate. > > Thanks in advance > > -- > Posted via http://www.ruby-forum.com/. > > class MyClass end class_name = 'MyClass' klass = Kernel.const_get(class_name) # => MyClass klass.new # => # Note that this doesn't work if your class is namespaced by a module or other class. If that is the case, you'll have to look up older discussions on the topic, or use something like ActiveSupport's constantize require 'active_support' module MyMod class MyClass end end class_name = 'MyMod::MyClass' klass = class_name.constantize # => MyMod::MyClass klass.new # => # --0016361e847c298b6e049aee427e--