Log in
updated 11:29 AM UTC, May 4, 2016

Ruby Program to count number of words in a String

  • Written by Madhu V Rao
  • Published in Ruby

Let us look into a program which counts the number of words in a String using Ruby.

def count_words(str)
  wordCount = {}
  str.downcase.scan(/\b[\w]*\b/).each do |word|
    next if  word.empty?
    if wordCount[word] == nil || wordCount[word] == ''
     wordCount[word] = 1
    else
      wordCount[word] = (wordCount[word]+1)
    end
  end
  return wordCount
end

The above function takes a String as its argument and process it word by word (regex - '\b[\w]*\b').

For each word it adds it to a Hash with value 1( if not already present) or increment the value counter (if already present).

Test the function by adding code as following

count_words("A man, a plan, a canal -- Panama")

Powered by Bullraider.com
Follow Us on Twitter
Find Us on Facebook
Follow Us on Google
Follow Us on Pinterest