MenTaLguY
1/12/2006 4:55:00 PM
Quoting Joshua Muheim <forum@josh.ch>:
> Joshua Muheim wrote:
> > This already anwers my question, thank you. :-)
>
> Hrm oke, got another related question.
>
> array1 = [1,2,4,6]
> array2 = [1,3,5,6]
>
> Is there an easy way for doing this?
>
> array1 ?? array2 = [1,6] # Only add entries that occur in both
> arrays
array1 & array2
Here, you're finding the intersection of two sets.
> array1 ?? array2 = [2,3,4,5] # Only add entries that occur in one
> of both arrays
There are at least two ways to do this:
( array1 | array2 ) - ( array1 & array2 )
or
( array1 - array2 ) | ( array2 - array1 )
Some people call this "exclusion"; it's the inverse of intersection.
However, at this point you might want to consider using Set rather
than Array. Performing set operations on Arrays is not very
efficient.
To use Set, require 'set'. You can create a set like:
Set[1, 3, 5, 6]
or (from an array):
Set[*array]
The set operations union, intersection, and difference (|, &, -)
work the same for sets as they do arrays, and Set also implements
Enumerable (so you get Set#each, Set#to_a, etc...).
Ah, one additional thing -- if you want exclusion, there is a
shorter way to write it with sets:
set1 = Set[1, 2, 4, 6]
set2 = Set[1, 3, 5, 6]
set1 ^ set2 # => #<Set: {5, 2, 3, 4}>
Note that sets are unordered containers.
-mental