Ruby Tuesday – Array#&

Today’s Ruby Tuesday continues on with the Array class and takes a look at Array#*.

Array#* does a set intersection between two arrays1, and an empty array is treated as an empty set.

[1, 2, 3, 4, 5] & []
# => []
[1, 2, 3, 4, 5] & [1, 3, 5]
# => [1, 3, 5]
[1, 2, 3, 4, 5] & [1, 3, 5, 7, 9]
# => [1, 3, 5]
[:a, :b, :c, :d] & [:a, 2, :foo]
# => [:a]
[:d] & [:a, :b, :c, :d]
# => [:d]

The Ruby documentation pages mentions that it uses the eql? and hash methods to determine if two elements are equal, so the elements only have to have the same value and not be the same reference.

[[1, 2], [3, 4], ["a", "b"]] & [[3, 4]]
# => [[3, 4]]
[3, 4].equal? [3, 4]
# => false
[3, 4].eql? [3, 4]
# => true

Array#& also keeps the order of the items as found in the original list for the items in the return value.

["a", "b", "c", "d", "e"] & ["c", "a", "t"]
# => ["a", "c"]

And as mentioned above, it is a set intersection, so no matter how many times an item appears in either array, it is only returned once.

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

And by turning a String into an Array of characters, we can find all characters that are common between two strings.

"Supercalifragilisticexpialidocious".chars & "Me Ol' Bamboo".chars
# => ["e", "a", "l", "o"]

–Proctor


1. For those who are unfamiliar with what a set intersection is, it is finds all unique elements that are common between the two arrays.

Leave a Reply

Your email address will not be published. Required fields are marked *