Newbie: Reflection question(?)

G

Gaudi Mi

At runtime I have the name of a class in a string, and I want to call a
method on the class having that name. How do I do that?

E.g., let's say that we have several classes that all have a method
called address().
At run-time I know I want to call the method address() on a particular
class, and that class name is in a string.

Thanks.
G
 
K

Kev Jackson

Gaudi said:
At runtime I have the name of a class in a string, and I want to call a
method on the class having that name. How do I do that?

E.g., let's say that we have several classes that all have a method
called address().
At run-time I know I want to call the method address() on a particular
class, and that class name is in a string.
you need to look at call

eg to instantiate an object (call Object.new)

m = c.method:)new)
o = m.call

to call address method

m = c.method:)address)
m.call

Kev
 
G

Gaudi Mi

I'll try that, thanks Kev!

G


Kev said:
you need to look at call

eg to instantiate an object (call Object.new)

m = c.method:)new)
o = m.call

to call address method

m = c.method:)address)
m.call

Kev
 
R

Ross Bamford

At runtime I have the name of a class in a string, and I want to call a
method on the class having that name. How do I do that?

Here are two possible ways:

str = "Array"
# => "Array"

ary_clz = eval(str)
# => Array

ary_clz.class
# => Class

ary_clz.new
# => []

##################

ary_clz = Object.const_get(str)
# => Array

ary_clz.new
# => []
 
R

Robert Klemme

Ross Bamford said:
At runtime I have the name of a class in a string, and I want to call a
method on the class having that name. How do I do that?

Here are two possible ways:

str = "Array"
# => "Array"

ary_clz = eval(str)
# => Array

ary_clz.class
# => Class

ary_clz.new
# => []

##################

ary_clz = Object.const_get(str)
# => Array

ary_clz.new
# => []

const_get is definitely preferred as it doesn't show the same security
risks as eval does.

Addtional note, for nested class names:

name.split(/::/).inject(Object) {|cl,n| cl.const_get(n)}.address()

Kind regards

robert
 
B

Benjohn Barnes

you need to look at call

eg to instantiate an object (call Object.new)

m = c.method:)new)
o = m.call

I don't think that's going to work for him (if c is the
name_of_class_string that he's got). He needs to look up the class
named name_of_class_string:

ObjectSpace.const_get(name_of_class_string).new(*any_arguments)

I'd like to check that is the "right way" to do it, but I don't have
any reference books to hand.
 

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

Similar Threads


Members online

No members online now.

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,667
Latest member
DaniloB294

Latest Threads

Top