DEV Community

Toni Oriol
Toni Oriol

Posted on • Originally published at Medium on

Difference, Union and Intersection in Ruby arrays

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 only present in 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]

Source: https://www.endpoint.com/blog/2011/06/07/using-set-operators-with-ruby-arrays

Top comments (0)