[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Class.forName ?

RCS

5/16/2005 12:54:00 AM

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
4 Answers

Park Ji-In

5/16/2005 1:05:00 AM

0

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
=> []




David Naseby

5/16/2005 1:05:00 AM

0

On 5/16/05, baalbek <rcs@bgoark.no> wrote:
> In Java there is a construct like this:
>
> Class clazz = Class.forName("Person");
>

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

Lots of other ways, I'm sure.


--
David Naseby
http://homepages.ihug.com.a...


Mark Hubbart

5/16/2005 1:25:00 AM

0

On 5/15/05, baalbek <rcs@bgoark.no> wrote:
> 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?

Perhaps you want:

Person = 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 = Object.const_set("Person", Class.new)

person = klass.new

HTH,
Mark


RCS

5/16/2005 1:26:00 AM

0

Park Ji-In wrote:
> irb(main):006:0> Class.const_get('Array').new

Ahh, exactly what I needed! Thanks!

Baalbek