Dynamically instantiate a class

Hi.

I’ve been wondering if I can instantiate during execution, I have this
subclasses, but I don’t know how to do it by their name as a string.

This is what I mean:

class superClass

end

class subClass1 < superClass

end

class subClass2 <superClass

end

class caller
type = [‘subClass1’,‘subClass2’]

def create_class(var)
#instantiate class type[var]
newClass = type[var].new # ???
end
end

I don’t wanna do it with a case clause, cos I don’t know when I’m going
to
add more subclasses.

Any idea?

I’ve found this:

def create_class(var)
#instantiate class type[var]
foo = Object.const_get(type[var])
sub = foo.new
puts “#{sub.class}”
end

Works for me!

On Feb 6, 2008 8:32 PM, macaco [email protected] wrote:

I’ve found this:

def create_class(var)
#instantiate class type[var]
foo = Object.const_get(type[var])
sub = foo.new
puts “#{sub.class}”
end

Works for me!
So you’re not creating a class, really. You’re creating an instance of
already-defined classes. Right?

You can smash those down to one line and get rid of your holder
variable, if you like:

def create_thing var
sub = Object.const_get(type[var]).new
puts sub.class
end

I’m not a huge fan of holder variables, myself, but your mileage may
vary, of course.

Ben

On Feb 6, 2008, at 9:32 PM, macaco wrote:

I’ve found this:

def create_class(var)
#instantiate class type[var]
foo = Object.const_get(type[var])
sub = foo.new
puts “#{sub.class}”
end

Works for me!

Or you could do this:

def create_class klass
klass.new
end

create_class “subClass1” #=> #

BTW, can you have a class name that’s NOT a constant?

-------------------------------------------------------|
~ Ari
if god gives you lemons
YOU FIND A NEW GOD

macaco wrote:

type = [‘subClass1’,‘subClass2’]

def create_class(var)
#instantiate class type[var]
newClass = type[var].new # ???
end

If you change the first line into

type = [SubClass1, SubClass2] #without quotes

the above works as-is.

HTH,
Sebastian

On Feb 7, 2008, at 10:22 AM, fedzor wrote:

Or you could do this:

def create_class klass
klass.new
end

create_class “subClass1” #=> #

Whoops! This should be:

create_class subClass1

when you create a class, it assigns the class to the name you give it

--------------------------------------------|
If you’re not living on the edge,
then you’re just wasting space.