Ruby Tuesday – Array#-

Today’s Ruby Tuesday is on Array#-.

Array#-, also called Array Difference, operates against an array, takes another array as its argument, and returns the items in the source array that are not in the second array.

[1, 2, 3, 4, 5] - [1, 2, 3, 5, 8]
# => [4]
[1, 2, 3, 4, 5] - [1, 2, 3, 6, 7, 8]
# => [4, 5]
[1, 2, 3, 6, 7, 8] - [1, 2, 3, 4, 5]
# => [6, 7, 8]
["a", "b", "c", "d"] - ["a", "s", "d", "f"]
# => ["b", "c"]
["a", "b", "c", "d"] - []
# => ["a", "b", "c", "d"]
[] - ["a", "s", "d", "f"]
# => []

As it is doing a difference between the two arrays, let’s add in some duplicate items and see what happens.

[1, 1, 2, 3, 5] - [2, 4, 6, 8]
# => [1, 1, 3, 5]
[1, 2, 2, 3,] - [2, 4, 6, 8]
# => [1, 3]

Based on the results we see that if there was a duplicate item in the source list that wasn’t in the second array, then we leave all those items in the source list.

If we have an item that is duplicated in the first list, and has an entry in the second list as well, then all occurences of that item get removed.

If we wanted more of a set difference behavior, we would have to either call uniq on at least the first array, if not both, or call uniq on the result of the difference.

[1, 1, 2, 3, 5].uniq - [2, 4, 6, 8].uniq
# => [1, 3, 5]
(main)> ([1, 1, 2, 3, 5] - [2, 4, 6, 8]).uniq
# => [1, 3, 5]

–Proctor