From: Carl Porth Date: 2007-10-10T06:56:22+09:00 Subject: Re: Finding shared elements between to arrays. I think the operation you are looking for is a set intersection. In Ruby, it is the & method. >> ['a', 'b', 'c', 'd'] & ['c', 'd', 'e', 'f'] => ["c", "d"] Carl On Oct 9, 2: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? > > Well... here are the two solutions that seemed the most obvious to me. I > profiled them and the second one performed a little better: > > a1 = ['a', 'b', 'c', 'd'] > a2 = ['c', 'd', 'e', 'f'] > a3 = [] > > #Solution 1 > a1.each { |e| a3 << e if a2.include?(e) } > > #Solution 2 > a3 = a1.map { |e| e if a2.include?(e) } > a3.compact! > > Info from the profiler: > % cumulative self self total > time seconds seconds calls ms/call ms/call name > 41.56 29.29 29.29 400000 0.07 0.11 Array#include? > 28.31 49.24 19.95 100000 0.20 0.68 Array#each > 22.06 64.79 15.55 1100000 0.01 0.01 String#== > 4.19 67.74 2.95 200000 0.01 0.01 Array#<< > 3.89 70.48 2.74 1 2740.00 70480.00 Integer#upto > 0.00 70.48 0.00 1 0.00 70480.00 #toplevel > > % cumulative self self total > time seconds seconds calls ms/call ms/call name > 43.82 28.24 28.24 400000 0.07 0.11 Array#include? > 23.32 43.27 15.03 1100000 0.01 0.01 String#== > 22.25 57.61 14.34 100000 0.14 0.58 Array#map > 8.50 63.09 5.48 1 5480.00 64450.00 Integer#upto > 2.11 64.45 1.36 100000 0.01 0.01 Array#compact! > 0.00 64.45 0.00 1 0.00 64450.00 #toplevel > > Thanks in advance! > > Best regards > Sebastian > -- > Posted viahttp://www.ruby-forum.com/.