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
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.
klass = Kernel.const_get(myVariable)
foo = klass.new
See Module.const_get. Also, you can store a constant reference in a
variable too, so you can have the following too:
my_variable = my_class # note, I am not using a string here
foo = my_variable.new
P.S : underscored names are preferred over camel case in Ruby :).
On Fri, Jan 28, 2011 at 2:39 PM, Rick T. [email protected] wrote:
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 # => #MyClass:0x41753c
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 # => #MyMod::MyClass:0x49f0c4