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
MediumRead a single line of input, a sentence. Analyze it and print three lines:
- The number of unique words (case-insensitive, with punctuation stripped). Repeated words count once each.
- The repeated words (those appearing more than once), sorted alphabetically, joined with
,. If none, print(none). - 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, racecarCheat 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 }.sortPrint (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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier