Ruby Array Set Operators

Have you ever had an array that you only want to include unique elements?
1
2
3
4
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 |
.