From: Robert Klemme Date: 2006-02-02T06:45:58+09:00 Subject: Re: Loop weirdness Jonathan Leighton wrote: > On Tue, 2006-01-31 at 05:03 +0900, Robert Klemme wrote: >> 2006/1/30, Jonathan Leighton : >>> On Mon, 2006-01-30 at 05:33 +0900, Simon Kræ—¦ger wrote: >>>> Jonathan Leighton wrote: >>>> >>>>> Hi, >>>>> >>>>> I'm going ever so slightly crazy over some looping behaviour. >>>>> Here's a simplified test case I made: >>>> >>>> Is this what you are trying to do? >>>> >>>> def categorise(items) >>>> items.inject(Hash.new([])) do |h, item| >>>> h[item[:num]] += [item[:foo]]; h >>>> end.map{|k, v| {:num => k, :items => v}} >>>> end >>> >>> That's cool (although crowded), but it doesn't fit the bill for me >>> as I need the order to be retained. >> >> What exactly do you want to do? Can you describe it other than in >> code? Input, output etc. > > I did, back in the thread a little: Sorry, that slipped by me. > ---- > These are interesting but unfortunately I need the order of the > original > items array to be maintained. This is because for the *actual* > purpose, > it's sorting a number of rows from a database and categorising them > by a > date field. The rows are returned in a certain order from the database > and that order must be kept. > ---- That description sounds as if a straightforward hash solution would work: def cat(records) ha = Hash.new {|h,k| h[k]=[]} records.each do |rec| ha[rec[:date]] << rec end ha end But apparently that's not what you want. (Is it?) You could of course return two items (records and ha) from this method to preserve original order. Cheers robert