From: Sean O'Halpin Date: 2008-11-28T03:30:30+09:00 Subject: Re: Ruby's duck typing On Thu, Nov 27, 2008 at 5:10 PM, stephan.zimmer wrote: > I would like to represent certain data by a list; to this end I let > class SomeData inherit from Array: > > class SomeData < Array > def get_field > self[2] > end > end > > (I want to keep it simple, therefore, the example might look silly.) > Since the "get_field" method is not universal I don't want to reopen > class "Array". If I write > > SomeData.new([1,2,3]).get_field > > everything is fine. If I, however, try to do > > [1,2,3].get_field > > I get an exception "NoMethodError", which, of course, is not > surprising. > > My question is: is there a way around this, that is, to simply write > [1,2,3] to denote a constant of type "SomeData" instead of always > writing "SomeData.new([1,2,3])" (without reopening Array)? > > Thanks a lot, > > Stephan > > The short answer is no. A technique that a (select ;) few of us favour is to define factory methods like this: def SomeData(*a, &b) SomeData.new(*a, &b) end so you can write: a = SomeData [1,2,3] You might also want to have a look at Ara Howard's arrayfields: http://www.codeforpeople.com/lib/ruby/arrayfields/. Latest version docs here: http://www.codeforpeople.com/lib/ruby/arrayfields/arrayfields-4.6.0/README Having said all that, subclassing core classes tends to throw up a host of fiddly issues. Robert's suggestion to use delegation instead is a good one where your class doesn't need to be considered as a kind of Array (in this case). Regards, Sean