From: Robert Klemme Date: 2006-05-07T02:53:46+09:00 Subject: Re: Creating sub-classes using Struct 2006/5/6, Eli Bendersky : > Hello, > > There are two Ruby features I want to combine. One is sub-classes (or > embedded classes): > > class Foo > def initialize(x) > puts "new Foo #{x}" > end > > class Bar > def initialize(y) > puts "new Bar #{y}" > end > end > end > > > joe = Foo::Bar.new(12) # prints "new Bar 12" > > > Another is dynamic creation of new classes using Struct: > > Customer = Struct.new(:name, :address) #=> Customer > eddy = Customer.new("Dave", "123 Main") > > Here 'Customer' is a class and 'eddy' is an instance of the Customer > class. > > Now, by combining the features, I mean creating a subclass of Foo > dynamically, using Struct. The following pseudo-code demonstates it > (pseudo because it obviously doesn't work and only shows what I'm trying > to do): > > class Foo > def initialize(x) > puts "new Foo #{x}" > end > > Bar = Struct.new(:name, :address) > end > > eddy = Foo::Bar.new("Dave", "123 Main") > > > How can this be done ? You'll have to modify Struct to be able to create sub classes of arbitrary classes and not just Object. Btw, if feels a bit strange to have a nested class that is a sub class of the outer class. By that twist it contains itself - I think this is not a good idea. Kind regards robert -- Have a look: http://www.flickr.com/photos/fussel-foto/