March 27 - Finding All Duplicates in an Array in Ruby
Ruby has a helpful method for removing duplicates from an array, the uniq method. However, there are times when you simply want to know which elements in an array are duplicates. In this guide we'll add a method to the Array class that returns all duplicates. Additionally, I'll examine two approaches to the solution and discuss the benefits of each option.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
  • Complete the Exercise
Video locked
This video is viewable to users with a Bottega Bootcamp license

Summary

Build a method that returns all of the duplicates from an array in Ruby.

Exercise Description

Add a new method to Ruby's Array class that returns all duplicate values.

Example Input/Output

ints = [1, 2, 1, 4]
ints.find_duplicates # => [1]

invoices = [
  { company: 'Google', amount: 500, date: Date.new(2017, 01, 01).to_s, employee: 'Jon Snow' },
  { company: 'Yahoo',  amount: 500, date: Date.new(2017, 01, 01).to_s, employee: 'Jon Snow' },
  { company: 'Google', amount: 500, date: Date.new(2015, 07, 31).to_s, employee: 'Jon Snow' },
  { company: 'Google', amount: 500, date: Date.new(2017, 01, 01).to_s, employee: 'Jon Snow' },
  { company: 'Google', amount: 500, date: Date.new(2017, 01, 01).to_s, employee: 'Jon Snow' },
  { company: 'Google', amount: 500, date: Date.new(2017, 01, 01).to_s, employee: 'Jon Snow', notes: 'Some notes' },
  { company: 'Google', amount: 500, date: Date.new(2017, 01, 01).to_s, employee: 'Jon Snow', notes: 'Some notes' },
]

invoices.find_duplicates

# => [
# =>   {:company=>"Google", :amount=>500, :date=>'2017-01-01', :employee=>"Jon Snow"},
# =>   {:company=>"Google", :amount=>500, :date=>'2017-01-01', :employee=>"Jon Snow"},
# =>   {:company=>"Google", :amount=>500, :date=>'2017-01-01', :employee=>"Jon Snow", :notes=>"Some notes"}
# => ]

Real World Usage

I got the idea for this exercise when I accidentally submitted a duplicate expense into Freshbooks and the system did a great job in letting me know that I may have a potential duplicate expense. Additionally, Ruby has a very helpful Array class method, uniq, that removes all duplicates from an array. However, Ruby doesn't have a simple way to find all duplicates in a collection, so this will help you examine how to parse through arrays efficiently to return all of the duplicate values.

Test Cases

Code File