0
0
RubyHow-ToBeginner · 3 min read

How to Remove Duplicates from Array in Ruby Easily

In Ruby, you can remove duplicates from an array using the uniq method, which returns a new array without repeated elements. To modify the original array directly, use uniq!.
📐

Syntax

The uniq method is called on an array to return a new array with duplicates removed. The uniq! method modifies the original array in place and returns nil if no changes were made.

  • array.uniq: Returns a new array without duplicates.
  • array.uniq!: Removes duplicates from the original array.
ruby
array = [1, 2, 2, 3, 4, 4, 5]
unique_array = array.uniq
array.uniq!
💻

Example

This example shows how to remove duplicates from an array using uniq and uniq!. It prints the original array, the new array without duplicates, and the original array after modification.

ruby
array = [1, 2, 2, 3, 4, 4, 5]

puts "Original array: #{array}"

unique_array = array.uniq
puts "New array without duplicates: #{unique_array}"

array.uniq!
puts "Original array after uniq!: #{array}"
Output
Original array: [1, 2, 2, 3, 4, 4, 5] New array without duplicates: [1, 2, 3, 4, 5] Original array after uniq!: [1, 2, 3, 4, 5]
⚠️

Common Pitfalls

One common mistake is expecting uniq! to always return an array. It returns nil if no duplicates were found and the array was not changed. Also, using uniq without assignment does not change the original array.

Example of wrong and right usage:

ruby
# Wrong: uniq does not change original array
array = [1, 2, 2, 3]
array.uniq
puts array.inspect  # Output: [1, 2, 2, 3]

# Right: assign uniq result or use uniq!
unique = array.uniq
puts unique.inspect   # Output: [1, 2, 3]

array.uniq!
puts array.inspect   # Output: [1, 2, 3]
Output
[1, 2, 2, 3] [1, 2, 3] [1, 2, 3]
📊

Quick Reference

Here is a quick summary of methods to remove duplicates from arrays in Ruby:

MethodDescriptionModifies Original Array?
uniqReturns a new array without duplicatesNo
uniq!Removes duplicates in place, returns nil if no changeYes

Key Takeaways

Use uniq to get a new array without duplicates without changing the original.
Use uniq! to remove duplicates directly from the original array.
uniq! returns nil if no duplicates were found and no changes made.
Always assign the result of uniq if you want to keep the duplicate-free array.
Remember that uniq and uniq! work on arrays of any object type.