1 min read

Keeping array elements uniq in Ruby

Syed Aslam

With the

uniq
method you can remove duplicate elements from an array.

irb> array = []
=> []
irb> array << 1
=> [1]
irb> array << 2
=> [1, 2]
irb> array << 1
=> [1, 2, 1]
irb> array.uniq
=> [1, 2]

However, calling

uniq
removes the duplicate elements and returns a new array with unique elemnts. It won't change the original array. You can use
uniq!
to remove duplicates in place.

Another way is to only append an element if the array does not already contain it using the

|
.

irb> array = []
=> []
irb> array << 1
=> [1]
irb> array << 2
=> [1, 2]
irb> array | [1]
=> [1, 2]
irb> array
=> [1, 2]

And to update the array in place if it doesn't contain the element:

irb> array |= [3]
=> [1, 2, 3] 
irb> array
 => [1, 2, 3]

Cover photo by Markus Winkler