From: dblack@... Date: 2007-08-09T20:26:59+09:00 Subject: Re: Collect objects from an array based on one unique parame Hi -- On Thu, 9 Aug 2007, Milo Thurston wrote: > Robert Klemme wrote: >> selection = things.select {|x| x.name = "foo"} > > That is closer, but still not quite it. > A slight change of my previously posted code may make it clearer. In > this case I start with an array of "Thing" objects called "things", and > would like an array called "uniquely_named_things" containing Things > where the name is unique. > > > check = Hash.new > uniquely_named_things = Array.new > things.each do |s| > if check[s.name].nil? > uniquely_named_things << s > end > check[s.name] = 1 > end > > Basically, I wonder if anything that does the same as this has already > been included in Ruby. I don't think so. It might be handy to generalize it: module UniqBy def uniq_by res = [] count = Hash.new(0) each do |item| y = yield(item) if y count[y] += 1 if count[y] == 1 res << item else res.delete(item) end end end res end end Thing = Struct.new(:name) a = Thing.new("David") b = Thing.new("John") c = Thing.new("David") d = Thing.new("Mary") e = Thing.new("Joe") things = [a,b,c,d,e].extend(UniqBy) p things.uniq_by {|thing| thing.name } Another way to do this, which I imagine is much slower, is: things.select do |thing| things.select {|other| other.name == thing.name }.size == 1 end David -- * Books: RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242) RUBY FOR RAILS (http://www.manning.com/black) * Ruby/Rails training & consulting: Ruby Power and Light, LLC (http://www.rubypal.com)