Class.forName("Array")


(Sylvia Chai) #1

Is it possible to create an object of the class
’Class’ dynamically?

Fox example: to create an object of ‘Class’ with the
value of ‘Hash’ by something like: Class.new(‘Hash’)
or Class.forName(‘Hash’)

Isn’t it very useful?

···

Do You Yahoo!?
Sign up for SBC Yahoo! Dial - First Month Free
http://sbc.yahoo.com


(Joel VanderWerf) #2

Sylvia Chai wrote:

Is it possible to create an object of the class
’Class’ dynamically?

Fox example: to create an object of ‘Class’ with the
value of ‘Hash’ by something like: Class.new(‘Hash’)
or Class.forName(‘Hash’)

How about Class.new(Hash)? This creates an anonymous subclass of Hash.

If you assign to a constant, like this:

MyHash = Class.new(Hash)

then the subclass will be associated with the name ‘MyHash’:

p MyHash.new.class ==> MyHash


(James) #3

Is it possible to create an object of the class
’Class’ dynamically?

Fox example: to create an object of ‘Class’ with the
value of ‘Hash’ by something like: Class.new(‘Hash’)
or Class.forName(‘Hash’)

Isn’t it very useful?

There was code for this posted on ruby-talk not too long ago, by Dave
Thomas (I think):

def for_name(className)
ObjectSpace.each_object(Class) do |c|
return c if c.name == className
end
raise "Class #{className} not found"
end

···

Do You Yahoo!?
Sign up for SBC Yahoo! Dial - First Month Free
http://sbc.yahoo.com


(Nobuyoshi Nakada) #4

Hi,

Is it possible to create an object of the class
’Class’ dynamically?

Fox example: to create an object of ‘Class’ with the
value of ‘Hash’ by something like: Class.new(‘Hash’)
or Class.forName(‘Hash’)

eval(‘Hash’).new

Or

Object.const_get(‘Hash’).new

Isn’t it very useful?

Probably. But Class.new creates anonymous subclass for the
argument, and forName doesn’t look so good.

···

At Thu, 4 Jul 2002 03:31:22 +0900, Sylvia Chai wrote:


Nobu Nakada


(Massimiliano Mirra) #5

Is it possible to create an object of the class
’Class’ dynamically?

Fox example: to create an object of ‘Class’ with the
value of ‘Hash’ by something like: Class.new(‘Hash’)
or Class.forName(‘Hash’)

irb(main):001:0> name = ‘Hash’
"Hash"
irb(main):002:0> klass = Module.const_get(name)
Hash
irb(main):003:0> h = klass.new
{}

Isn’t it very useful?

It is. :slight_smile:

Massimiliano

···

On Thu, Jul 04, 2002 at 03:31:22AM +0900, Sylvia Chai wrote: