Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Array#intersection

array.intersection(*other_arrays) → new_array

Returns a new Array containing each element found both in self and in all of the given Arrays other_arrays; duplicates are omitted; items are compared using eql?:

Example
[0, 1, 2, 3].intersection([0, 1, 2], [0, 1, 3]) # => [0, 1]
[0, 0, 1, 1, 2, 3].intersection([0, 1, 2], [0, 1, 3]) # => [0, 1]

Preserves order from self:

Example
[0, 1, 2].intersection([2, 1, 0]) # => [0, 1, 2]

Returns a copy of self if no arguments given.

Related: Array#&.

See also #intersect? #join #inspect #keep_if also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0