From: Robert Klemme Date: 2005-07-07T16:40:47+09:00 Subject: Re: Inheriting Array and slice() behaviour Patrick Gundlach wrote: > [...] > >> OTOH, inheriting classes like Array is seldom really good. >> There are too many methods that return plain arrays and you end up >> with Arrays anyway. Delegation, ad hoc modification or extension >> with a Module is often better. > > Now it is the second time I've read this. Currently I have a class > that stores an 8 bit encoding. The elements of this class are accessed > directly just like an array. So now I have > > class ENC < Array > > attr_accessor :foo > > def initialize(fileobject=nil) > # if fileobject then initialize 256 elements with the contents > # of the file > # else > # super(256,"undefined slot") > end > def somefunction > # read the contents of the 256 and store the result of > # some operation in @foo > end > end > > So I get [], []= and a lot of things for free. My subclass is basicly > an array with some additional methods attached. What do you suggest > instead? Something like > > class ENC < DelegateClass(Array) > ... > end Yep. Or do it selectively (what I'd prefer). This can help: class Module def delegate(member, method) class_eval "def #{method}(*a,&b) @#{member}.#{method}(*a,&b) end" end end >> class Foo >> def initialize() @s = "foo" end >> ?> delegate :s, :size >> end "def size(*a,&b) @s.size(*a,&b) end" => nil >> Foo.new.size => 3 Btw, IMHO this would be a good addition to delegate.rb. What do others think? Kind regards robert