/ Tags: RUBY-CODE / Categories: SOLUTIONS

Count Word Frequency In A String In Ruby

Counting how often each word appears in a string is a common text-processing task — useful for analytics, content analysis, keyword detection, and building word clouds. Ruby’s Enumerable provides an idiomatic one-liner.

Description

Split the string into words, normalize case and punctuation, then use tally (Ruby 2.7+) to count occurrences. For pre-2.7, each_with_object or group_by + transform_values achieve the same result. The key steps: downcase for case-insensitive counting, strip punctuation with gsub so “Ruby” and “Ruby,” count as the same word, split on whitespace, then tally. Sorting by frequency (most common first) is done with sort_by on the resulting hash.

Sample input:

  text = "Ruby is great. Ruby is fast. Rails uses Ruby."


Sample Output:

  { "ruby" => 3, "is" => 2, "great" => 1, "fast" => 1, "rails" => 1, "uses" => 1 }

Answer

  def word_frequency(text)
    text.downcase
        .gsub(/[^a-z\s]/, "")
        .split
        .tally
        .sort_by { |_, count| -count }
        .to_h
  end

  # Ruby < 2.7 alternative (without tally)
  def word_frequency_legacy(text)
    text.downcase.gsub(/[^a-z\s]/, "").split
        .each_with_object(Hash.new(0)) { |word, counts| counts[word] += 1 }
        .sort_by { |_, count| -count }.to_h
  end

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