Ruby Array Set Operators


Have you ever had an array that you only want to include unique elements?

In this example we’re combining list_1 and list_2, then removing duplicate entries using the #uniq method before assigning to the combined_list variable.

Another approach would be to not include duplicate elements all together using one of the array set operators: the union operator |.

Union |

The union operator combines the unique values of two sets. Here we’re using this set operator to generate the same result using two arrays.

Difference -

The difference operator returns the difference between two sets. Just like the previous example, we’ll use arrays.

What’s on the left side of the difference operator is important. It takes elements on the left (in our case the elements in the array) and compares them to the elements on the right; and the elements that are different are returned.

So in the example above, list_1 is on the left (['a', 'b', 'c']) and list_2 is on the right ['c', 'd', 'e'].

The elements in list_1 that are different (not included in) from the elements in list_2 are the ones that are returned ["a", "b"].

list_2 difference

We could easily see what elements are in list_2 that are not included in list_1 by placing list_2 on the left side of the difference operator.

Intersection &

The intersection operator returns the elements that are common in both sets. It’s easy to think of intersection and difference as opposites.