Open In App

How to Merge Two Arrays and Remove Values that have Duplicates?

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to merge two arrays and remove values that have duplicate Ruby. We can merge two arrays and remove values that have duplicates through various methods provided in Ruby.

Using the | Operator

The | Operator merges two arrays and removes duplicate values.

Syntax:

array1 | array2

Example: 

In this example, the | operator is used to merge array1 and array2, removing duplicate values.

Ruby
# Example arrays
array1 = [1, 2, 3, 4]
array2 = [3, 4, 5, 6]

# Merge arrays and remove duplicates 
# using the | operator
result = array1 | array2

# Output the result
puts "Merged array without duplicates: #{result}"

Output
Merged array without duplicates: [1, 2, 3, 4, 5, 6]

Using the uniq Method

The uniq method merges two arrays and removes duplicate values.

Syntax:

(array1 + array2).uniq

Example: 

In this example, the uniq method is used after merging array1 and array2 to remove duplicate values.

Ruby
# Example arrays
array1 = [1, 2, 3, 4]
array2 = [3, 4, 5, 6]

# Merge arrays and remove duplicates 
# using the uniq method
result = (array1 + array2).uniq

# Output the result
puts "Merged array without duplicates: #{result}" 

Output
Merged array without duplicates: [1, 2, 3, 4, 5, 6]

Using the Concat with uniq Method

The concat method first concatenates two arrays and then removes duplicate values using uniq.

Syntax:

(array1.concat(array2)).uniq

Example: 

In this example, the concat method is used to concatenate two arrays and then removes duplicate values using uniq

Ruby
# Example arrays
array1 = [1, 2, 3, 4]
array2 = [3, 4, 5, 6]

# Merge arrays and remove duplicates 
# using the concat and uniq methods
result = (array1.concat(array2)).uniq

# Output the result
puts "Merged array without duplicates: #{result}"

Output
Merged array without duplicates: [1, 2, 3, 4, 5, 6]

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads