拡張子別にファイル数をカウントします。
file_count.rb
#! /usr/bin/env ruby
require 'pathname'
@directories = 0
@files = {}
def file_count(pathname)
pathname.each_child do |child|
if child.directory?
@directories += 1
file_count child
else
add_file_by_extenstion child
end
end
end
def add_file_by_extenstion(pathname)
if @files[pathname.extname].nil?
@files[pathname.extname] = 1
else
@files[pathname.extname] += 1
end
end
if ARGV[0]&.start_with? '-'
puts <<-EOT
usage: file_count {directory}
EOT
exit
end
unless ARGV[0].nil?
file_count Pathname.new(ARGV[0])
else
file_count Pathname.new('.')
end
puts "#{@directories}\tdirectories"
@files.each do |extension, count|
if extension == ""
puts "#{count}\tno extension"
else
puts "#{count}\t#{extension}"
end
end