Ruby - Merge two arrays and remove values that have duplicate

Use |

a = [1, 2, 3, 4, 5]
b = [2, 4, 6]

Merge without duplicating values

a | b 
# => [1, 2, 3, 4, 5, 6]

Get only duplicate values

a & b
# => [2, 4]

Merge and remove values that were duplicated. Which means getting all unique values and subtracting all duplicate values.

(a | b) - (a & b)
# => [1, 3, 5, 6]

Ruby Docs


You can do the following!

# Merging
c = a + b
 => [1, 2, 3, 4, 5, 2, 4, 6]
# Removing the value of other array
# (a & b) is getting the common element from these two arrays
c - (a & b)
=> [1, 3, 5, 6]

Dmitri's comment is also same though I came up with my idea independently.


Use Array#uniq.

a = [1, 3, 5, 6]
b = [2, 3, 4, 5]

c = (a + b).uniq
=> [1, 3, 5, 6, 2, 4]