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
array.c
View on GitHub ↗
static VALUE
rb_ary_union_multi(int argc, VALUE *argv, VALUE ary)
{
int i;
long sum;
VALUE hash;
sum = RARRAY_LEN(ary);
for (i = 0; i < argc; i++) {
argv[i] = to_ary(argv[i]);
sum += RARRAY_LEN(argv[i]);
}
if (sum <= SMALL_ARRAY_LEN) {
VALUE ary_union = rb_ary_new();
rb_ary_union(ary_union, ary);
for (i = 0; i < argc; i++) rb_ary_union(ary_union, argv[i]);
return ary_union;
}
hash = ary_make_hash(ary);
for (i = 0; i < argc; i++) rb_ary_union_hash(hash, argv[i]);
return rb_hash_values(hash);
}
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.