Robert Klemme
10/10/2007 6:48:00 AM
2007/10/10, Eric I. <rubytraining@gmail.com>:
> On Oct 9, 5:46 pm, Sebastian probst Eide
> <sebastian.probst.e...@gmail.com> 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) }
Just a caveat: for large Arrays it might be inefficient (I don't know
how it's implemented). You might want to look at class Set:
irb(main):001:0> require 'set'
=> true
irb(main):002:0> [ 1, 1, 3, 5 ].to_set.intersection [ 1, 2, 3 ]
=> #<Set: {1, 3}>
Kind regards
robert