Skip to content

Instantly share code, notes, and snippets.

@bakkdoor
Created April 10, 2009 12:03
Show Gist options
  • Save bakkdoor/93057 to your computer and use it in GitHub Desktop.
Save bakkdoor/93057 to your computer and use it in GitHub Desktop.
# find all words in file and sort them by appearance count
def print_file(filename = "test.rb")
File.open(filename, "r") do |f|
word_hash = {} # same as Hash.new
while(not f.eof)
line = f.readline
line.split(/\s+/).each do |word|
if(word_hash[word])
word_hash[word] += 1
else
word_hash[word] = 1
end
end
end
sorted_word_hash = word_hash.sort_by{|key,value| value}
# print out sorted words with each word's counter value
puts "words in file sorted by appearance counter:"
# word = key, count = value
sorted_word_hash.select{|word,count| not word.gsub(" ", "").empty?}.each do |word, count|
puts "#{count}: #{word}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment