Difference, Union and Intersection in Ruby arrays
1 min readAug 10, 2018
It’s done with basic operators instead of methods: -
for difference, |
for union, and &
for intersection.
An important detail is that all duplicated items are automatically removed. Which allows to make an array unique finding the intersection between itself: [1, 1, 2] & [1, 1, 2] = [1, 2]
.
Difference
[1, 2, 3] - [3, 4, 5] = [1, 2][3, 4, 5] - [1, 2, 3] = [4, 5]
In summary, it returns the unique values from the first array.
Union
[1, 2, 1, 2, 3] | [1, 2, 3, 4] = [1, 2, 3, 4]
Intersection
[1, 1, 3, 5] & [1, 2, 3] = [1, 3]