From: "Eric I." Date: 2008-05-29T04:48:31+09:00 Subject: Re: Merge collections of objects On May 28, 8:55 am, John Butler wrote: > Hi, > > I wonder if there is a quick way to do this. > > companyA has 2 employees "a", "b" > > companyB has 3 employees "a", "b", "c" > > I basically want to merge companyA employess with companyB employees so > when i look at companyA the employees will equal "a", "b", "c" Hi John, It's interesting that you used the word "collections" in your subject rather than "arrays". Because Ruby has options when it comes to collections, and you can often gain something by choosing the best collection for the job rather than always resorting to Arrays and Hashes. And it's also worth considering what types of operations you'll be performing on these collections and how many members you expect to deal with. I don't know how Array#uniq is implemented, but it's most typically implemented as an O(n**2) or it creates a supplementary data structure (e.g., hash) to help it along. The class Set is in the standard library, and as you might imagine a set is a collection that does not allow duplicates and that does not maintain order. So it will automatically handle your "problem" of duplicates. The question is whether maintaining order is important to your application or not. And if you're merging a Set of size n into one of size m, the merge is likely O(n) with no huge memory requirement (as typically implemented). So it's likely more efficient at this operation. Here's some sample code: require 'set' company_a = Set.new ['alice', 'bob', 'carla'] company_b = Set.new ['david', 'bob', 'ellen'] print "The employee(s) common to both companies is ", (company_a & company_b).to_a.join(', '), ".\n" new_company = company_a + company_b puts "If we create a new company with a union, we get " + #{new_company.inspect}." company_a.merge(company_b) puts "If we merge one company into the other, we get " + #{company_a.inspect}." Eric ==== LearnRuby.com offers Rails & Ruby HANDS-ON public & ON-SITE workshops. Ruby Fundamentals Wkshp June 16-18 Ann Arbor, Mich. Ready for Rails Ruby Wkshp June 23-24 Ann Arbor, Mich. Ruby on Rails Wkshp June 25-27 Ann Arbor, Mich. Ruby Plus Rails Combo Wkshp June 23-27 Ann Arbor, Mich Please visit http://LearnRuby.com for all the details.