Class.forName ?

B

baalbek

In Java there is a construct like this:

Class clazz = Class.forName("Person");

Person person = (Person)clazz.newInstance();

Is there something similar available for Ruby, that is, can I create a
class on the fly only having this class' name as a string?

In other words, something like this (for Ruby):

person = Class.new("Person")

This does not work, but is there something that would work like this?

Thanks in advance!

Baalbek
 
D

David Naseby

In Java there is a construct like this:
=20
Class clazz =3D Class.forName("Person");
=20

irb(main):001:0> class A; def initialize; puts 'in A'; end; end
=3D> nil
irb(main):002:0> a =3D eval("A.new")
in A
=3D> #<A:0x2ad3400>
irb(main):003:0> a =3D Module.const_get("A").new
in A
=3D> #<A:0x2ad02c8>

Lots of other ways, I'm sure.


--=20
David Naseby
http://homepages.ihug.com.au/~naseby/
 
P

Park Ji-In

2005-05-16 (월), 09:55 +0900, baalbek 쓰시길:
In other words, something like this (for Ruby):

person = Class.new("Person")

how about

irb(main):006:0> Class.const_get('Array').new
=> []

or

irb(main):007:0> Class.const_get:)Array).new
=> []
 
M

Mark Hubbart

In Java there is a construct like this:
=20
Class clazz =3D Class.forName("Person");
=20
Person person =3D (Person)clazz.newInstance();
=20
Is there something similar available for Ruby, that is, can I create a
class on the fly only having this class' name as a string?
=20
In other words, something like this (for Ruby):
=20
person =3D Class.new("Person")
=20
This does not work, but is there something that would work like this?

Perhaps you want:

Person =3D Class.new
or
Object.const_set "Person", Class.new

Both will create a new class named "Person". The second method will
let you use a name determined at runtime. If I understand your Java
code above, the Ruby translation would be something like this:

klass =3D Object.const_set("Person", Class.new)
=20
person =3D klass.new

HTH,
Mark
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top