From: "David A. Black" Date: 2008-07-22T20:22:21+09:00 Subject: Re: Grouping/Sorting an Array of objects Hi -- On Mon, 21 Jul 2008, Howard Roberts wrote: > Suppose I have an array of two different kinds of objects, each with > different attributes, but both having a date attribute. I'd like to be > able to loop through the array in such a manner as to be able print a > result similar to the following: > > > 07/19/08 > Foo-1 - Name > attr 1 > attr 2 > [..] > > Foo-2 - Name > attr 1 > attr 2 > [..] > > Bar - Name > attr 1 > attr 2 > [..] > 07/20/08 > Foo-1 - Name > attr 1 > attr 2 > [..] > > Bar - Name > attr 1 > attr 2 > [..] > etc. > > showing all of the Foo's first, then the Bar's, for each date. > If I only have Foo's, I can easily do: > > @data.sort{|x,y| Time.parse(x.date) <=> Time.parse(y.date)}).each do > |foo| > puts Foo.date # Still shows date on each loop, but okay > puts Foo.name > [..] > end > > To get things in date order, but when I consider mixing a second object > into the array, that confounds matters for me. I suspect group_by{|item| > item.class} may be part of the solution, but I'm not sure how? > > Any pointers would be most appreciated. Here's a stab at it: http://pastie.org/238521. I've put the sorting intelligence in the objects, and also given them to_s methods so you don't have to do all that formatting in the calling code (though you can, of course, if you want a different output). The last ten lines still seem a bit wordy to me but so be it; I have to go get ready for work :-) David -- Rails training from David A. Black and Ruby Power and Light: Intro to Ruby on Rails July 21-24 Edison, NJ * Advancing With Rails August 18-21 Edison, NJ * Co-taught by D.A. Black and Erik Kastner See http://www.rubypal.com for details and updates!