Ruby adds Array#intersection method

1 minute read

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.

[ 1 , 1 , 3 , 5 ]. intersection ([ 3 , 2 , 1 ]) #=> [ 1, 3 ] [ "a" ]. intersection #=> [ "a" ]

You can also pass multiple arrays as arguments to the method,

[ "a" , "b" , "z" ]. intersection ([ "a" , "b" , "c" ], [ "b" ]) # => [ "b" ]

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.

[ "a" , "b" , "c" ]. union ( [ "c" , "d" , "a" ] ) #=> [ "a", "b", "c", "d" ] [ "a" ]. union #=> [ "a" ]

Like Array#intersection , you can pass multiple arrays as arguments to the method,

[ 1 , 2 , "a" ]. union ([ 1 , 27 , "a" ], [ 2 , "I" ]) #=> [ 1, 2, "a", 27, "I" ]

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.

[ 1 , 4 , 7 , 8 , "a" , :t ]. difference ([ 4 , :t ]) #=> [ 1, 7, 8, "a" ]

Again, multiple arrays as arguments can be passed to the method,

[ 1 , 4 , 7 , 8 , "a" , :t ]. difference ([ 4 , :t ], [ "a" ]) #=> [ 1, 7, 8 ]