Skip to content

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

instance method

Array#union

[T] (*::Array[T] other_arys) -> ::Array[T | Elem]
union(*other_arrays) → new_array

Returns a new array that is the union of the elements of self and all given arrays other_arrays; items are compared using eql?:

Example
[0, 1, 2, 3].union([4, 5], [6, 7]) # => [0, 1, 2, 3, 4, 5, 6, 7]

Removes duplicates (preserving the first found):

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

Preserves order (preserving the position of the first found):

Example
[3, 2, 1, 0].union([5, 3], [4, 2]) # => [3, 2, 1, 0, 5, 4]

With no arguments given, returns a copy of self.

Related: see Methods for Combining.

See also #transpose #uniq #to_s #uniq! also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0