From: Robert Klemme Date: 2004-08-31T15:40:25+09:00 Subject: Re: Flexible operations for a collection class "Edgardo Hames" schrieb im Newsbeitrag news:478c16ae040830134175316839@mail.gmail.com... > On Tue, 31 Aug 2004 05:25:26 +0900, Robert Klemme wrote: > > > > > > > > but I would like to implement the #<=> method in my objects, so I can > > > delegate the #sort method to @elements. I came up with this, > > > > > > def sortable_by=(element_attribute) > > > @sortable_by=element_attribute > > > @elements.each{|o| o.sortable_by=@sortable_by} > > > end > > > > Putting the comparison criteria into the elements is very bad design. What > > will you do if your elements are in two different collections at the same > > time? The sorting criterium belongs into the collection. > > > From The Pickaxe Book, in the Enumerable Module > > "Mix in Enumerable, and suddenly your class supports things such as > map, include?, and find_all?. If the objects in your collection > implement meaningful ordering semantics using the <=> method, you'll > also get min, max, and sort." > > That's the reason behind my design. Yeah, but <=> just gives you the default ordering (e.g. lexical for strings and numeric for fixnum). As far as I can see, that's not what you wanted: you wanted to be able to define the order yourself. Changing <=> all the time is not a good idea because of the issue with multiple collections as well as other pieces of code relying on the natural ordering. Btw, see also Comparable. http://www.rubycentral.com/book/ref_m_comparable.html > But, the Set solution satisfies > most of my needs. I just need to add a few methods to it. Fine! > Thanks for your clear response. You're welcome. robert