blairanderson
3/24/2017 - 12:32 AM

Ruby: Union and Intersection Guide ( Pipe | and Ampersand & operators )

Ruby: Union and Intersection Guide ( Pipe | and Ampersand & operators )

Ruby Array Pipe | (Union) and Ampersand &(Intersection) operators

&, intersection, overlap

The ampersand is an array method that returns the overlapping items.

ary & other_ary → new_ary

Also known as Set Intersection

Returns a new array containing elements common to the two arrays, excluding any duplicates. The order is preserved from the original array.

[ 1, 1, 3, 5 ] & [ 1, 2, 3 ]                 #=> [ 1, 3 ]
[ 'a', 'b', 'b', 'z' ] & [ 'a', 'b', 'c' ]   #=> [ 'a', 'b' ]

| Pipe, Union, merge and de-duplicate

The pipe is an array method that will merge the two arrays and maintain order(from the first array) if a duplicate exists in the second array.

ary | other_ary → new_ary Also known as Set Union

Returns a new array by joining ary with other_ary, excluding any duplicates and preserving the order from the original array.

[ "a", "b", "c" ] | [ "c", "d", "a" ]    #=> [ "a", "b", "c", "d" ]