Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Array#union
[T] (*::array[T] other_arrays) -> ::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)
{
rb_len_t sum = RARRAY_LEN(ary);
for (int 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 (int i = 0; i < argc; i++) rb_ary_union(ary_union, argv[i]);
return ary_union;
}
VALUE set = rb_obj_hide(rb_set_new_capa(sum));
rb_ary_union_set(set, ary);
for (int i = 0; i < argc; i++) rb_ary_union_set(set, argv[i]);
return rb_set_to_a(set);
}
Returns a new array that is the union of the elements of self and all given arrays other_arrays; items are compared using eql? and hash:
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.