Tuesday, December 02, 2008

Ruby Fiber


   1  #!/usr/local/bin/ruby

   2  # encoding: utf-8

   3  words = Fiber.new do

   4    File.foreach("testfile") do |line|

   5      line.scan(/\w+/) do |word|

   6        Fiber.yield word.downcase

   7      end

   8    end

   9  end

  10  counts = Hash.new(0)

  11  while word = words.resume

  12    counts[word] += 1

  13  end

  14  counts.sort { |a,b| b[1] <=> a[1] }.each { |w| print "#{w[1]}:#{w[0]} " }

No comments: