Taking cue from Array#union and Array#difference methods added to Ruby 2.6, Ruby has now added Array#intersection
method which is an alias for Array#&.
The purpose behind these additions is to make the methods more clean and readable than their operator counterparts.
Lets take a look at what each method does,
Array#intersection
The Array#intersection
method returns a new array containing elements common to both arrays. The order is preserved from original array.
Since its a set operation, the resultant array has unique elements.
You can also pass multiple arrays as arguments to the method,
Array#union
Another set operation, Array#union
returns a new array by joining other arrays with itself, excluding any duplicates. The order is preserved from given arrays.
Like Array#intersection
, you can pass multiple arrays as arguments to the method,
Array#difference
As its name suggests, Array#difference
returns a new array with items from receiver after removing items that appear in both receiver and array given as arguments. The order is preserved from original array.
Again, multiple arrays as arguments can be passed to the method,
Note that all above mentioned methods compare elements using their hash
and eql?
methods for efficiency.