Recap - Frequency Counter
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 37 of 56.
Pull together default-valued hashes, iteration, and sorting from the previous chapters into one classic challenge: a word frequency report.
Challenge
MediumRead a single line of input, a sentence. Build a Hash.new(0) mapping each word (split on whitespace, lowercased) to its frequency.
Then print:
- The total number of unique words
- One line per word in descending frequency (ties broken alphabetically by word) in this format:
<word>: <count>
For input the quick brown fox jumps over the lazy dog the dog, the output is:
8
the: 3
dog: 2
brown: 1
fox: 1
jumps: 1
lazy: 1
over: 1
quick: 1Try it yourself
input = gets.chomp
# TODO: build a Hash.new(0) of word → count, then print:
# 1) the number of unique words
# 2) entries sorted by count desc, ties by word asc
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