Menu
Coddy logo textTech

Word Analytics

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 54 of 56.

A standalone challenge that pulls on strings, hashes, Hash.new(0), and Enumerable methods all at once.

challenge icon

Challenge

Medium

Read a single line of input, a sentence. Analyze it and print three lines:

  1. The number of unique words (case-insensitive, with punctuation stripped). Repeated words count once each.
  2. The repeated words (those appearing more than once), sorted alphabetically, joined with , . If none, print (none).
  3. The palindrome words, words that read the same forwards and backwards, length ≥ 2, sorted alphabetically, joined with , . If none, print (none).

Strip the characters .,!?:;"() from each word before processing. Lowercase everything for comparison.

For input Madam saw a racecar. Dad said hello hello to mom., the output is:

9
hello
dad, madam, mom, racecar

Cheat sheet

Use Hash.new(0) to count word frequencies, then use Enumerable methods to filter and sort:

words = line.gsub(/[.,!?:;"()]/, '').downcase.split
freq = Hash.new(0)
words.each { |w| freq[w] += 1 }

unique = freq.keys
repeated = freq.select { |_, v| v > 1 }.keys.sort
palindromes = unique.select { |w| w.length >= 2 && w == w.reverse }.sort

Print (none) when a collection is empty:

puts repeated.empty? ? "(none)" : repeated.join(", ")

Try it yourself

input = gets.chomp

# TODO: split, strip punctuation, lowercase, then print:
#   unique count, repeated words, palindromes (length >= 2)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow