wcを作る

Rubyでwcを作ってみました。

files = 0
total_lines = total_words = total_chars = 0
ARGV.each do |pattern|
  Dir.glob(pattern) do |file|
    open(file, "r") do |f|
      f.binmode
      files += 1
      lines = words = chars = 0
      while line = f.gets
        lines += 1
        chars += line.length
        line.scan(/\S+/) do |w|
          words += 1
        end
      end
      printf("%8d%8d%8d %s\n", lines, words, chars, file.to_s)
      total_lines += lines
      total_words += words
      total_chars += chars
    end
  end
end
if files > 0
  printf("%8d%8d%8d %s\n", total_lines, total_words, total_chars, "total")
end

使ったもの:

  • ARGV.each do |arg| ... end
  • Dir.glob(pattern)
  • IO#binmode
  • String#scan