From: Brian Candler Date: 2007-02-09T00:55:53+09:00 Subject: Re: Grouping similar attributes On Fri, Feb 09, 2007 at 12:12:42AM +0900, Dominic Son wrote: > How would one group attributes which came from an array/db? > > For example in my DB: > > --------------------- > | NAME | ETHNIC | > -------------------- > | Dominic | Asian | > --------------------- > | John | Asian | > --------------------- > | Rick | Spanish | > --------------------- > > I'd like it to group by Ethnicity: > > Asian > - Dominic > - John > > Spanish > - Rich > > > Is there some ruby thing that makes this convenient? d = { 'Dominic' => 'Asian', 'John' => 'Asian', 'Rick' => 'Spanish', } # Unfortunately this doesn't quite do what you want: i = d.invert puts i.inspect # So: j = Hash.new { [] } d.each { |k,v| j[v] <<= k } puts j.inspect