Ruby Array Set Operators

Ruby Array Set Operators

How to use set operators to find the union, difference and intersection of two arrays in ruby

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

list_1 = ['apple', 'orange', 'grape']
list_2 = ['strawberry', 'apple']
combined_list = (list_1 + list_2).uniq
combined_list #=> ["apple", "orange", "grape", "strawberry"]

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.

list_1 = ['apple', 'orange', 'grape']
list_2 = ['strawberry', 'apple']
combined_list = list_1 | list_2
combined_list #=> ["apple", "orange", "grape", "strawberry"]

Difference -

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

list_1 = ['a', 'b', 'c']
list_2 = ['c', 'd', 'e']
list_1_difference = list_1 - list_2
list_1_difference #=> ["a", "b"]

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.

list_1 = ['a', 'b', 'c']
list_2 = ['c', 'd', 'e']
list_1_difference = list_2 - list_1
list_1_difference #=> ["d", "e"]

Intersection &

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

list_1 = ['a', 'b', 'c']
list_2 = ['c', 'd', 'e']
common_elements = list_1 & list_2
common_elements #=> ["c"]