/ Tags: RUBY-CODE / Categories: SOLUTIONS

Find Duplicate Elements In An Array In Ruby

Detect which values appear more than once in an array using group_by or tally.

Description

Duplicate detection comes up in data validation, deduplication pipelines, and form processing. Ruby’s tally method (3.0+) counts occurrences in one pass — filter for count > 1 to get duplicates. For broader compatibility, group_by with a size check works identically.

Sample input:

  values = [1, 2, 3, 2, 4, 1, 5]


Sample Output:

   [1, 2]

Answer

    # Ruby 3.0+ — tally counts occurrences
    values = [1, 2, 3, 2, 4, 1, 5]

    duplicates = values.tally.filter_map { |val, count| val if count > 1 }
    # => [1, 2]

    # Broader compatibility — group_by
    duplicates = values.group_by { |v| v }
                       .select { |_, group| group.size > 1 }
                       .keys
    # => [1, 2]

Learn More

cdrrazan

Rajan Bhattarai

Full Stack Software Developer! 💻 🏡 Grad. Student, MCS. 🎓 Class of '23. GitKraken Ambassador 🇳🇵 2021/22. Works with Ruby / Rails. Photography when no coding. Also tweets a lot at TW / @cdrrazan!

Read More