How to Count Duplicate Elements in a Ruby Array

09/21/2021

Contents

In this article, you will learn how to count duplicate elements in a Ruby array.

Count duplicate elements in a Ruby array

To count duplicate elements in a Ruby array, you can use the group_by method to group the elements by their value and then use the count method to count the number of elements in each group.

Here is an example code snippet that demonstrates this approach:

array = [1, 2, 3, 2, 4, 3, 5, 6, 5, 7, 8, 8]

# Group the elements by their value
groups = array.group_by(&:itself)

# Count the number of elements in each group
counts = groups.map { |value, group| [value, group.count] }

# Select only the groups that have more than one element
duplicates = counts.select { |value, count| count > 1 }

# Print the duplicates
duplicates.each do |value, count|
  puts "#{value} appears #{count} times"
end

In this example, the array contains 12 elements, including several duplicates. The group_by method is used to group the elements by their value, resulting in a hash where the keys are the unique values in the array and the values are arrays containing the elements that have that value.

Next, the map method is used to transform the hash into an array of pairs, where the first element in each pair is a value from the array and the second element is the number of times that value appears in the array.

The select method is then used to filter the array to only include pairs where the count is greater than one, indicating that the value appears more than once in the array.

Finally, the duplicates are printed out with a message indicating how many times each duplicate appears in the array.