From: "Eric I." Date: 2007-10-10T07:05:08+09:00 Subject: Re: Finding shared elements between to arrays. On Oct 9, 5:46 pm, Sebastian probst Eide wrote: > Hi > I am wondering if there is a really smart built in way to get an array > which has the elements shared by two other arrays? I made two > "solutions" myself, but I am wondering what other people are using, and > if there is a preferred solution to the task? array.union(other_array) > or something like that? The & operator, as defined on Arrays, performs an intersection operation. >From the RDoc: > array & other_array > ------------------------------------------------------------------------ > Set Intersection---Returns a new array containing elements common > to the two arrays, with no duplicates. > > [ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ] Also, another tip: rather than using a combination of map and compact!, you could instead use select, as in: a3 = a1.select { |e| a2.include?(e) } Best, Eric ---- Are you interested in on-site Ruby training that's been highly reviewed by former students? http://LearnRuby.com