Menu
Coddy logo textTech

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 icon

Challenge

Medium

Read a single line of input, a sentence. Build a Hash.new(0) mapping each word (split on whitespace, lowercased) to its frequency.

Then print:

  1. The total number of unique words
  2. 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: 1

Try 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