Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Array#&

(::Array[untyped] | ::_ToAry[untyped]) -> ::Array[Elem]
self & other_array → new_array

Returns a new array containing the intersection of self and other_array; that is, containing those elements found in both self and other_array:

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

Omits duplicates:

Example
[0, 1, 1, 0] & [0, 1] # => [0, 1]

Preserves order from self:

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

Identifies common elements using method eql? (as defined in each element of self).

Related: see Methods for Combining.

See also .try_convert #* .new #+ also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0