File: countwords.rb

Project: Invitation to Ruby

#!/usr/bin/env ruby

words = Hash.new(0)
while line = gets
  for word in line.scan(/\b[A-Za-z]+\b/)
    words[word] += 1
  end
end
sortedwords = words.sort do |a, b|
  (b[1] <=> a[1]).nonzero? ||
    (a[0] <=> b[0])
end
sortedwords.each do |word, count|
  puts "#{word}: #{count}"
end


[ Index ][ Table of Contents ]
Generated by [ source2html ]