Class.forName?

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

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.

···

On 5/16/05, baalbek <rcs@bgoark.no> wrote:

In Java there is a construct like this:

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

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

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

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

···

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?

Park Ji-In wrote:

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

Ahh, exactly what I needed! Thanks!

Baalbek