From: "Ara.T.Howard" Date: 2005-07-08T02:57:30+09:00 Subject: Re: Inheriting Array and slice() behaviour On Fri, 8 Jul 2005, William Morgan wrote: > Excerpts from Robert Klemme's mail of 6 Jul 2005 (EDT): >> I wouldn't be so certain of this. It's normal for operations like >> #dup and #clone to behave that way. Also, part of the smartness of >> ruby is that you can simply do self.class.new to get a new instance of >> the same class. And often you need to create an instance of the same >> class. That's not too abnormal. > > Dup and clone work on objects that have already been initialized. > Self.class.new is done explicitly, so that's fine too---if the > constructor has required arguments, you supply them at that point. > > My problem with Array#slice is that the objects created will never have > #initialize called. Indeed, they never *can* have it called, because who > knows what arguments need to be supplied. it's this simple: harp:~ > cat a.rb class Expression < ::Array def initialize(*a, &b) init(*a, &b) end def init(*a, &b) @a, @b = a, b end def inspect {'a' => @a, 'b' => @b}.inspect end inited_return_methods = %w( slice ) inited_return_methods.each do |m| eval <<-definition def #{ m }(*a, &b) ret = super ret.init(*@a, &@b) ret end definition end end exp = Expression::new 'an arg', 'another arg' subexp = exp.slice 0,2 p subexp harp:~ > ruby a.rb {"a"=>["an arg", "another arg"], "b"=>nil} note that the subexp has the same values given to the ctor of the original exp. this will not be exactly what you want, but the approach is generic: * remember what args the object was initialized with * make a public initializer * use meta-programming to re-construct the methods you want such that return values are, in fact, initialized. if you remember what an object was initialized with it's always possible to re-initialize it or to initialize another object with those values - you need only decide the rules for doing so. hth. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | My religion is very simple. My religion is kindness. | --Tenzin Gyatso ===============================================================================