Dynamically instantiate a class

M

macaco

[Note: parts of this message were removed to make it a legal post.]

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?
 
M

macaco

[Note: parts of this message were removed to make it a legal post.]

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!
 
D

Day

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
 
S

Sebastian Hungerecker

macaco said:
=A0 =A0type =3D ['subClass1','subClass2']

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

If you change the first line into

type =3D [SubClass1, SubClass2] #without quotes

the above works as-is.

HTH,
Sebastian
=2D-=20
Jabber: (e-mail address removed)
ICQ: 205544826
 
F

fedzor

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" #=> #<subClass1>

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

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

fedzor

Or you could do this:

def create_class klass
klass.new
end

create_class "subClass1" #=> #<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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,153
Latest member
NamKaufman
Top