How to Use The Ruby Uniq Method To Remove Duplicates

With the uniq method you can remove ALL the duplicate elements from an array.

Let’s see how it works!

If you have an array like this one:

n = [1,1,1,2,3,4,5]

Where the number 1 is duplicated.

Calling uniq on this array removes the extra ones & returns a NEW array with unique numbers.



# [1,2,3,4,5]

Notice that uniq won’t change n (the original array), so we need to either call uniq!, or to save the new array.


unique_numbers = n.uniq

Pretty easy, right?

But a lot of people don’t know that uniq takes a block.

With a block, you can do more advanced things.

Let me explain…

How to Use Ruby Uniq Method With A Block

When you call uniq, it works by making a hash out of your array elements.

Every element becomes a key in the hash.

Because hash keys are unique, we can get a list of all the keys in the hash, this list then becomes our new array with unique elements.


If you want to change what makes something unique, you can pass a block.

Here’s an example:

fruits = %w(orange apple banana)

“Orange” and “Banana” have the same length of 6 characters.

If we use uniq like this:


# ["orange", "apple"]

Then we drop “banana” because it would be a duplicate when we compare the strings by their size.

Another example:

objects = [1, 2, "a", "b", :c, :d]


This gets you an array with unique objects by class:

[1, "a", :c]

Do you see the power of this?

When you pass a block to uniq, you’re able to define exactly by what rules something is considered unique.

How to Use Uniq With Multiple Conditions

You can use multiple conditions!

Here’s how:

Let’s say you have a User class, with:

  • age
  • name
  • country

You want only one person per country of the same age.

Easy with a block:

[david, petter, raphael].uniq { |person| [person.age,] }

With this code, both conditions have to match before something can be considered unique.

How Does This Work?

Without a block, the object becomes the hash key.

With a block, the yielded value becomes the hash key, and the object becomes the hash value.


Ruby takes the values & returns them as a new array.

These are just implementation details, but I find them very interesting so I thought I would share them with you.


You have learned about the uniq method in Ruby! Exactly how to use it, why is it useful, and how it works.

Now practice with this method so you can remember it.

Thanks for reading!

6 thoughts on “How to Use The Ruby Uniq Method To Remove Duplicates”

  1. Thanks for this.

    Instead of using “group_by” and then calling uniq on each array, this is simple and elegant.

Comments are closed.