dynamic object creation

A

Aryeh Friedman

If I have something like this:

s="Array"

How whould I get something like this:

aObject=s.new

In "plain" english I am asking if I have a valid name of a class in a
string how do I create an instance of the class the string contains?
 
S

Simon Strandgaard

If I have something like this:

s="Array"

How whould I get something like this:

aObject=s.new

In "plain" english I am asking if I have a valid name of a class in a
string how do I create an instance of the class the string contains?


How about this ?

s="Array"
aObject=eval(s+".new")
 
S

stefano

If I have something like this:

s="Array"

How whould I get something like this:

aObject=s.new

In "plain" english I am asking if I have a valid name of a class in a
string how do I create an instance of the class the string contains?

s = "Array"
aObject = eval(s).new
 
B

Brian Candler

s = "Array"
aObject = eval(s).new

... and just hope nobody passes in s = "`rm -rf /*`" as a class name :-|

const_get will be much faster too, as it doesn't have to compile a piece of
code each time.
 
S

stefano

.. and just hope nobody passes in s = "`rm -rf /*`" as a class name :-|

obviously, if you don't check what you're passing to eval(), you deserve
all the bad things that could happen :)
const_get will be much faster too, as it doesn't have to compile a piece of
code each time.

that's true, I didn't think about it.
 
A

Anders Borch

Brian said:
Even if it didn't, you can easily convert strings to symbols and vice versa.

"Array".intern
=> :Array

hadn't seen that one, thanks =)
 
R

Robert Klemme

Brian Candler said:
A class name is just a constant, so something like

a = Module.const_get("Array").new

is what you need (Aside: what's the proper way to access 'the top-level
Module', or is the above correct?)

I think this does it

a = Kernel.const_get("Array").new

robert
 

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,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top