Skip to content

Instantly share code, notes, and snippets.

@esparkman
Created January 6, 2011 21:43
Show Gist options
  • Save esparkman/768657 to your computer and use it in GitHub Desktop.
Save esparkman/768657 to your computer and use it in GitHub Desktop.
output
def count_frequency(word_list)
counts = Hash.new(0)
for word in word_list
counts[word] += 1
end
counts
end
e: e
t: t
k: k
a: a
c: c
require_relative 'words_from_string.rb'
require_relative 'count_frequency.rb'
raw_text = %{
The problem breaks down into two parts. First, given some test as a
string, return a list of words. That sounds like an array. Then, build a
count for each distinct word. That sounds like a use for a hash---we can
index it with the word and use the corresponding entry to keep a count.
}
word_list = words_from_string(raw_text)
counts = count_frequency(word_list)
sorted = counts.sort_by {|word, count| count}
top_five = sorted.last(5)
for i in 0...5
word = top_five[i][0]
count = top_five[i][0]
puts "#{word}: #{count}"
end
def words_from_string(string)
string.downcase.scan(/[\w']+/)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment