From: James Edward Gray II Date: 2007-02-09T01:59:29+09:00 Subject: Re: Grouping similar attributes On Feb 8, 2007, at 9:12 AM, 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 Here's one idea: >> Person = Struct.new(:name, :ethnic) => Person >> people = [Person.new("Dominic", "Asian"), Person.new("John", "Asian"), Person.new("Rick, "Spanish")] ^C >> people = [Person.new("Dominic", "Asian"), Person.new("John", "Asian"), Person.new("Rick", "Spanish")] => [#, #, #] >> by_ethnic = Hash.new => {} >> people.each do |person| ?> (by_ethnic[person.ethnic] ||= Array.new) << person >> end => [#, #, #] >> by_ethnic => {"Asian"=>[#, #], "Spanish"=>[#]} Hope that helps. James Edward Gray II