Keeping Array Elements Unique in Ruby

Keeping Array Elements Unique in Ruby


ruby array tip
Last updated on

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]

By default, uniq returns a new array with unique elements—it doesn’t modify the original. If you want to update in place, use uniq!:

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

Using the | Operator

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

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]

Modern Alternatives

Today, Ruby developers often prefer using Sets from the standard library for uniqueness. Sets behave like arrays but enforce uniqueness automatically:

require "set"

set = Set.new
set << 1
set << 2
set << 1
# => #<Set: {1, 2}>

This approach avoids repeated checks and provides a cleaner, intention-revealing API.


You might also like

© 2025 Syed Aslam