From: Pit Capitain Date: 2005-07-08T06:00:00+09:00 Subject: Re: Struct-like behaviour in custom classes Levin Alexander schrieb: > How can I build a Class that works like the built-in "Struct" and > returns new anonymous classes based on arguments to MyClass.new? > > A simplified example: > > with_foo = MyClass.new(:foo) > one = with_foo.new > one.foo > > with_bar = MyClass.new(:bar) > two = with_bar.new > two.bar > > I tried to do: > > class MyClass > def self.new_class(method_name) > c = Class.new(self) > c.class_eval do > define_method(method_name) { puts "method #{method_name} called" } > end > return c > end > end > > How can I rename 'new_class' to 'new' without breaking 'new' in > derieved classes? Hi Levin, you have to redefine "new" in the anonymous classes to call the original Class.new method. One possibility is to use aliases: class MyClass class << self alias :org_new :new def new(method_name) Class.new(self) do class << self alias :new :org_new end define_method(method_name) do puts "method #{method_name} called" end end end end end Regards, Pit