Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > Class.forName ?

Reply
Thread Tools

Class.forName ?

 
 
baalbek
Guest
Posts: n/a
 
      05-16-2005
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
 
Reply With Quote
 
 
 
 
David Naseby
Guest
Posts: n/a
 
      05-16-2005
On 5/16/05, baalbek <(E-Mail Removed)> wrote:
> 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/


 
Reply With Quote
 
 
 
 
Park Ji-In
Guest
Posts: n/a
 
      05-16-2005
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
=> []




 
Reply With Quote
 
Mark Hubbart
Guest
Posts: n/a
 
      05-16-2005
On 5/15/05, baalbek <(E-Mail Removed)> wrote:
> 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


 
Reply With Quote
 
baalbek
Guest
Posts: n/a
 
      05-16-2005
Park Ji-In wrote:
> irb(main):006:0> Class.const_get('Array').new


Ahh, exactly what I needed! Thanks!

Baalbek
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off




Advertisments