Array coherences

Sometimes the coherence between two arrays have to be qualitatively determined. That means, which elements of the two arrays are the same or respectively which are not equal.

Congruence

Ruby provides an operator for arrays that finds all the elements that exist in both arrays:

[1, 2, 3, 3] & [2, 3, 4]
# => [2, 3]

Duplicates are filtered.

Divergence

In Ruby there is no dedicated operator for finding the two arrays diverging elements. However, the elements can be found by subtracting the arrays:

a = [1, 2, 3]
b = [2, 3, 4, 4]
(a - b) | (b - a)
# => [1, 4]

By means of the | operator the duplicates are also filtered out.

Unique total set

Basically the | operator is meant for finding the unique total set of two arrays. Certainly this could also be implemented as follows:

# bad
([1, 2, 3] + [2, 3, 4]).uniq
# => [1, 2, 3, 4]

However, the better implementation is the one with the | operator:

# good
[1, 2, 3] | [2, 3, 4]
# => [1, 2, 3, 4]