Created
April 10, 2009 12:03
-
-
Save bakkdoor/93057 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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