Array#union
The union method returns a new array containing all elements from the original array and any arrays passed as arguments. Duplicates are removed, with the first occurrence of each element preserved. The order of elements follows their first appearance across all arrays.
Ruby also provides the | operator as a convenient alternative syntax for union operations between two arrays.
Syntax
array | other_array
array.union(*other_arrays)
The | operator works with exactly two arrays, while the union method accepts multiple arrays as arguments.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
*other_arrays | Array | — | Arrays to combine with self (method form only) |
The | operator does not accept parameters—it always operates on exactly two arrays.
Examples
Basic usage with the | operator
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
a | b
# => [1, 2, 3, 4, 5, 6]
Using the method form with multiple arrays
a = [0, 1, 2, 3]
b = [4, 5]
c = [6, 7]
a.union(b, c)
# => [0, 1, 2, 3, 4, 5, 6, 7]
Handling duplicate values
a = [0, 1, 1]
b = [2, 1]
a.union(b)
# => [0, 1, 2]
Notice that the duplicate 1 appears only once in the result—the first occurrence is preserved.
Preserving order
a = [3, 2, 1, 0]
b = [5, 3]
c = [4, 2]
a.union(b, c)
# => [3, 2, 1, 0, 5, 4]
The order reflects where each element first appeared: 3 and 0 from a, 5 first appears in b, and 4 first appears in c.
With no arguments
a = [1, 2, 3]
a.union
# => [1, 2, 3]
When called with no arguments, union returns a copy of the original array.
Common Patterns
Combining unique tags
post1_tags = ["ruby", "rails", "tutorial"]
post2_tags = ["ruby", "performance", "rails"]
post3_tags = ["tutorial", "beginners"]
all_tags = post1_tags | post2_tags | post3_tags
# => ["ruby", "rails", "tutorial", "performance", "beginners"]
Building a whitelist
allowed_categories = ["news", "sports", "tech"]
user_selections = ["news", "entertainment", "sports", "tech", "news"]
allowed_categories | user_selections
# => ["news", "sports", "tech", "entertainment"]
Performance Notes
The union method uses a hash-based implementation for efficiency. When combining large arrays, this approach avoids the quadratic complexity you’d get from manually checking for duplicates.
The | operator is slightly faster for two-array operations since it doesn’t need to handle the variadic argument parsing.
See Also
- array::intersection — returns elements common to all arrays
- array::flatten — flattens nested arrays into a single array