/ Tags: RUBY-CODE / Categories: SOLUTIONS

Find The Most Frequently Occurring Element In An Array In Ruby

Count element occurrences and return the one that appears most often — useful for analytics, voting systems, and mode calculations.

Description

Use Enumerable#tally (Ruby 2.7+) to count occurrences into a hash, then max_by to find the element with the highest count. For older Ruby, use each_with_object or group_by as alternatives. For ties (multiple elements share the max count), max_by returns the first one encountered. Use select + max_by to retrieve all tied elements.

Sample input:

  votes = [:alice, :bob, :alice, :carol, :bob, :alice]


Sample Output:

  :alice  # appears 3 times

Answer

    votes = [:alice, :bob, :alice, :carol, :bob, :alice]

    # Ruby 2.7+ — tally then max_by
    votes.tally.max_by { |_, count| count }.first
    # => :alice

    # Get the count too
    votes.tally.max_by { |_, count| count }
    # => [:alice, 3]

    # Handle ties — return all elements with max count
    tally = votes.tally
    max_count = tally.values.max
    tally.select { |_, count| count == max_count }.keys
    # => [:alice]  (only alice has 3; for ties would return all tied elements)

    # Pre-Ruby 2.7
    votes.group_by(&:itself)
         .max_by { |_, arr| arr.length }
         .first
    # => :alice

    # Numeric mode
    [4, 7, 2, 7, 3, 7, 4].tally.max_by { |_, c| c }.first
    # => 7

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