From: Robert Klemme Date: 2011-03-26T00:33:28+09:00 Subject: Re: Dynamic classes On Fri, Mar 25, 2011 at 3:25 PM, PsiPro wrote: > So I am working on some metaprograming and have some questions about > how to get what I need out of dynamic classes. > > Right now I know I can define dynamic classes like so: > a) TestClass = Class.new > b) var_class = Class.new > > These work as expected but I need the functionality provided by case > A. Specifically I need to have the instances respond to .class > appropriately. .class for case B returns Class, while case A responds > TestClass Case b cannot return Class. You would rather see something like this: 16:10:04 ~$ ruby19 -e 'TestClass = Class.new; p TestClass.new.class; var_class = Class.new; p var_class.new.class' TestClass # > The reason I need to do this is that I want to dynamically generate > classes, including their names. How can I accomplish this? > > My desired results: > > variable = Class.new > variable.class.name == 'variable' Magic works only with constants. The first constant that a Class or Module instance is assigned determines its name. > OR, I need to be able to assign a dynamic constant name (I know I > know). 16:30:47 ~$ ruby19 -e 'x=Class.new;Object.const_set("Foo",x);p x, x.new.class' Foo Foo Why do you need this? Maybe you can do classes = {} classes["Foo"] = Class.new do def nifty_method 42 end end Now you can do obj = classes["Foo"].new You could even override Class#name or #to_s per instance to return the proper value, if you must have the class name... Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/