How to Use the Ruby uniq Method

09/23/2021

Contents

In this article, you will learn how to use the Ruby uniq method.

Using the uniq method

The uniq method is a built-in method in Ruby that allows you to remove duplicates from an array. It returns a new array with only unique elements, keeping the first occurrence of each element and removing any subsequent duplicates.

Here’s an example of how to use the uniq method:

fruits = ["apple", "banana", "orange", "apple", "kiwi", "banana"]
unique_fruits = fruits.uniq
puts unique_fruits.inspect

In this example, the fruits array contains duplicate elements, so we use the uniq method to create a new array called unique_fruits that contains only the unique elements of the fruits array. The inspect method is used to print out the contents of the unique_fruits array.

The output of this code would be:

["apple", "banana", "orange", "kiwi"]

Notice that the duplicate elements “apple” and “banana” have been removed, and only the first occurrence of each element is retained in the new array.

You can also use the uniq method with a block to specify a custom comparison. For example, if you have an array of hashes and you want to remove duplicates based on a particular key, you could do something like this:

people = [
  { name: "Alice", age: 30 },
  { name: "Bob", age: 25 },
  { name: "Alice", age: 35 },
  { name: "Charlie", age: 40 },
  { name: "Bob", age: 30 }
]

unique_people = people.uniq { |person| person[:name] }
puts unique_people.inspect

In this example, we use the uniq method with a block that specifies that we want to remove duplicates based on the :name key of each hash. The output of this code would be:

[
  { name: "Alice", age: 30 },
  { name: "Bob", age: 25 },
  { name: "Charlie", age: 40 }
]

Notice that only the first occurrence of each unique name is retained in the new array.