How to Use the Ruby uniq! Method



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

Using the uniq! method

The Ruby uniq! method is a useful tool for removing duplicate elements from an array.

Basic Usage

The uniq! method is used to remove duplicates from an array in place. This means that the method modifies the original array instead of returning a new one. To use the uniq! method, simply call it on the array that you want to modify:

array = [1, 2, 2, 3, 3, 3]
puts array #=> [1, 2, 3]

In this example, we have an array with six elements, but three of them are duplicates. We call the uniq! method on the array, which modifies it to remove the duplicate elements. The output of the program shows the modified array with only the unique elements remaining.

Return Value

The uniq! method returns nil if no changes were made to the array. This can be useful for checking whether or not duplicates were present in the original array. For example:

array = [1, 2, 3]
result = array.uniq!
puts result.inspect #=> nil

In this example, the original array doesn’t have any duplicates, so calling uniq! on it doesn’t modify it. The return value of the method is nil, which we can see by calling inspect on the result variable.

Block Syntax

The uniq! method also supports a block syntax for customizing how duplicate elements are handled. The block is called with two arguments, which are the two elements that are being compared. The block should return true if the elements are considered equivalent, and false otherwise. For example:

array = ["foo", "bar", "baz"]
array.uniq! {|a, b| a[0] == b[0]}
puts array #=> ["foo", "bar"]

In this example, we have an array of strings. We call uniq! on the array with a block that checks whether the first character of each string is the same. Since “foo” and “bar” both start with “f” and “b”, respectively, they are considered equivalent and “baz” is removed from the array.