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.

Example:

n.uniq # [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.

Example:

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.

Now:

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:

fruits.uniq(&:size) # ["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] objects.uniq(&:class)

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:

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

Easy with a block:

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

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

If you’re using ActiveRecord:

Use the group method to get the same effect as Ruby’s uniq, it’s faster because it happens at the database level.

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.

Then…

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.

Summary

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!