0
0
RubyHow-ToBeginner · 3 min read

How to Find Union of Arrays in Ruby: Simple Guide

In Ruby, you can find the union of two arrays using the | operator or the Array#union method. Both combine arrays and remove duplicates, returning a new array with unique elements from both.
📐

Syntax

The union of arrays in Ruby can be found using either the | operator or the Array#union method.

  • array1 | array2: Combines array1 and array2, removing duplicates.
  • array1.union(array2): Does the same as the | operator but as a method call.
ruby
union_array = array1 | array2
# or
union_array = array1.union(array2)
💻

Example

This example shows how to find the union of two arrays using both the | operator and the union method. It combines the arrays and removes duplicates.

ruby
array1 = [1, 2, 3, 4]
array2 = [3, 4, 5, 6]

union_with_operator = array1 | array2
union_with_method = array1.union(array2)

puts "Union with | operator: #{union_with_operator}"
puts "Union with union method: #{union_with_method}"
Output
Union with | operator: [1, 2, 3, 4, 5, 6] Union with union method: [1, 2, 3, 4, 5, 6]
⚠️

Common Pitfalls

One common mistake is using the + operator instead of |. The + operator concatenates arrays but does not remove duplicates.

Also, remember that | and union return a new array and do not modify the original arrays.

ruby
array1 = [1, 2, 3]
array2 = [3, 4]

# Wrong: Using + (duplicates remain)
wrong_union = array1 + array2

# Correct: Using |
correct_union = array1 | array2

puts "Wrong union with +: #{wrong_union}"
puts "Correct union with |: #{correct_union}"
Output
Wrong union with +: [1, 2, 3, 3, 4] Correct union with |: [1, 2, 3, 4]
📊

Quick Reference

Use this quick reference to remember how to find the union of arrays in Ruby:

OperationDescriptionExample
| operatorCombines arrays and removes duplicates[1,2] | [2,3] #=> [1,2,3]
union methodSame as | but as a method[1,2].union([2,3]) #=> [1,2,3]
+ operatorConcatenates arrays, keeps duplicates[1,2] + [2,3] #=> [1,2,2,3]

Key Takeaways

Use the | operator or Array#union method to find the union of arrays in Ruby.
Both methods combine arrays and remove duplicate elements.
Avoid using + operator if you want to remove duplicates, as it only concatenates.
Union operations return a new array and do not change the original arrays.
The union methods work with arrays of any element types.