James Gray
2/8/2007 4:59:00 PM
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")]
=> [#<struct Person name="Dominic", ethnic="Asian">, #<struct Person
name="John", ethnic="Asian">, #<struct Person name="Rick",
ethnic="Spanish">]
>> by_ethnic = Hash.new
=> {}
>> people.each do |person|
?> (by_ethnic[person.ethnic] ||= Array.new) << person
>> end
=> [#<struct Person name="Dominic", ethnic="Asian">, #<struct Person
name="John", ethnic="Asian">, #<struct Person name="Rick",
ethnic="Spanish">]
>> by_ethnic
=> {"Asian"=>[#<struct Person name="Dominic", ethnic="Asian">,
#<struct Person name="John", ethnic="Asian">], "Spanish"=>[#<struct
Person name="Rick", ethnic="Spanish">]}
Hope that helps.
James Edward Gray II