Skip to content

Instantly share code, notes, and snippets.

@sai43
Created October 15, 2014 05:11
Show Gist options
  • Save sai43/3f4e8314a63b5548bb0f to your computer and use it in GitHub Desktop.
Save sai43/3f4e8314a63b5548bb0f to your computer and use it in GitHub Desktop.
analyze a text file, counting the occurrence of each word
# using fibers count words number of occurences in a file
words = Fiber.new do
File.foreach("samp.txt") do |line|
line.scan(/\w+/) do |word|
Fiber.yield word.downcase
end
end
nil
end
counts = Hash.new(0)
while word = words.resume
counts[word] += 1
end
counts.keys.sort.each {|k| puts "#{k}:#{counts[k]} "}
#without using fibers count words occurences in a file
=begin
counts = Hash.new(0)
File.foreach("samp.txt") do |line|
line.scan(/\w+/) do |word|
word = word.downcase
counts[word] += 1
end
end
counts.keys.sort.each {|k| puts"#{k}:#{counts[k]} "}
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment