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
Spanish
Is there some ruby thing that makes this convenient?
Thanks a whole bunch.
Dominic
On Fri, Feb 09, 2007 at 12:12:42AM +0900, Dominic S. wrote:
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
On Feb 8, 2007, at 9:12 AM, Dominic S. wrote:
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 G. II
This can help you too…
def ethnic_group(e, n)
if @eg.nil?
@eg = {}
end
if @eg[e].nil?
@eg[e] = []
end
@eg[e] << n
return @eg
end
@eg = nil
ethnic_group(‘asian’, ‘domnic’)
ethnic_group(‘asian’, ‘john’)
ethnic_group(‘spanish’, ‘rich’)
p @eg
Looks good. that would’ve been nifty if there was a function to automate
this…for now looks like we’re rolling our own… i’ll be playing with
these suggestions. thanks.
SunRaySon wrote:
This can help you too…
def ethnic_group(e, n)
if @eg.nil?
@eg = {}
end
if @eg[e].nil?
@eg[e] = []
end
@eg[e] << n
return @eg
end
@eg = nil
ethnic_group(‘asian’, ‘domnic’)
ethnic_group(‘asian’, ‘john’)
ethnic_group(‘spanish’, ‘rich’)
p @eg
btw, I’m going with Brian’s technique as it’s the least to type : P and
it works beautifully… thanks again.
Dominic S. wrote:
Looks good. that would’ve been nifty if there was a function to automate
this…for now looks like we’re rolling our own… i’ll be playing with